<?php


namespace App\Models;


use App\Http\Controllers\Jobs\PublicSavePdfController;
use App\Jobs\ExcelTaskJob;
use App\Models\Common\Constant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class BaseModel extends Model
{

    private $type_detail = [6,7,8,9,10,12,15,16,17];//需要扣掉的锁定库存

    private $type_detail2 = [1,2,4,5,18];//需要扣掉的上架中库存

    private $type_detail3 = [1,2,4,5,6,7,8,9,10,12,15,16,17,18];//需要扣掉的锁定库存和上架中库存

    //1.仓库调拨入库 2.采购入库 3.手工入库 4.样品退回入库 5.订单退货入库 6.fba出库 7.仓库调拨出库 8.第三方仓出库 9.采购退货出库 10.样品调拨出库 11.手工出库 12.订单出库 13.工厂虚拟入库 14.工厂虚拟出库 15.验货申请 16.调货申请
    private $type_detail_arr = [
        '1'=>'仓库调拨入库','2'=>'采购入库','3'=>'手工入库','4'=>'样品退回入库','5'=>'订单退货入库','6'=>'fba出库','7'=>'仓库调拨出库',
        '8'=>'第三方仓出库','9'=>'采购退货出库','10'=>'样品调拨出库','11'=>'手工出库','12'=>'订单出库','13'=>'工厂虚拟入库',
        '14'=>'工厂虚拟出库','15'=>'验货申请','16'=>'调货申请','17'=>'组货出库','18'=>'组货入库'];


    private $out_type_detail_arr = ['6'=>'fba出库','7'=>'仓库调拨出库',
        '8'=>'第三方仓出库','9'=>'采购退货出库','10'=>'样品调拨出库','11'=>'手工出库','12'=>'订单出库',
        '14'=>'工厂虚拟出库','15'=>'验货申请','16'=>'调货申请','17'=>'组货出库'];

    const WAREHOUSE = [
        '1' => 'tongan_inventory',
        '2' => 'quanzhou_inventory',
        '3' => 'cloud_num',
        '4' => 'factory_num',
        '6' => 'deposit_inventory',
        '21' => 'direct_inventory',
        '23' => 'shenzhen_inventory'
    ];

    protected function getLimitParam($page, $limit)
    {
        if ($page == 1) {
            return 0;
        }
        return ($page - 1) * $limit;
    }

    public function powers($data)
    {
        $identity = "'" . implode("','", $data['identity']) . "'";
        $sql = "select pr.*
				       from xt_role_user_join ruj
				       left join (select prj.role_id, prj.power_id, p.*
				                         from xt_powers_role_join prj
				                         inner join xt_powers p on p.Id=prj.power_id
				                  ) as pr on pr.role_id = ruj.role_id
				       where ruj.user_id={$data['user_id']} and pr.identity in ({$identity})
				       group by pr.power_id";
        $power_list = json_decode(json_encode(db::select($sql)), true);

        $array = array();
        foreach ($power_list as $k => $v) {
            $array[] = $v['identity'];
        }

        $powers = array();
        foreach ($data['identity'] as $va) {
            if (in_array($va, $array)) {
                $powers[$va] = true;
            } else {
                $powers[$va] = false;
            }
        }
        return $powers;

    }


    //出库类型
    public function GetFieldTypeDetail(){
        return $this->type_detail;
    }

    //出库类型详情
    public function GetFieldOutTypeDetailArr(){
        return $this->out_type_detail_arr;
    }
       

    //所有需要扣除的库位库存类型
    public function GetFieldTypeDetail3(){
        return $this->type_detail3;
    }

    //已推送未入库库存
    public function GetFieldTypeDetail2(){
        return $this->type_detail2;
    }
    
    //出库类型详情
    public function GetFieldTypeDetailArr(){
        return $this->type_detail_arr;
    }

    //根据id获取用户信息
    public function GetUsers($id)
    {
        $res = Redis::Hget('datacache:users', $id);
        if (!$res) {
            $res = Db::table('users')->where('Id', $id)->first();
            if ($res) {
                Redis::Hset('datacache:users', $id, json_encode($res));
                $res = json_decode(json_encode($res), true);
            } else {
                $res = false;
            }
        } else {
            $res = json_decode($res, true);
        }
        return $res;
    }

    //根据id获取平台信息
    public function GetPlatform($id)
    {
        $res = Redis::Hget('datacache:platform', $id);
        if (!$res) {
            $res = Db::table('platform')->where('id', $id)->first();
            if ($res) {
                Redis::Hset('datacache:platform', $id, json_encode($res));
                $res = json_decode(json_encode($res), true);
            } else {
                $res = false;
            }
        } else {
            $res = json_decode($res, true);
        }

        return $res;
    }

    //根据ID获取尺寸颜色
    public function GetColorSize($id)
    {
        $res = Redis::Hget('datacache:self_color_size', $id);
        if (!$res) {
            $res = Db::table('self_color_size')->where('id', $id)->first();
            if ($res) {
                Redis::Hset('datacache:self_color_size', $id, json_encode($res));
                $res = json_decode(json_encode($res), true);
            } else {
                $res = false;
            }
        } else {
            $res = json_decode($res, true);
        }

        return $res;
    }

    //根据ID获取店铺
    public function GetShop($id)
    {
        $res = Redis::Hget('datacache:shop', $id);
        if (!$res) {
            $res = Db::table('shop')->where('id', $id)->first();
            if ($res) {
                Redis::Hset('datacache:shop', $id, json_encode($res));
                $res = json_decode(json_encode($res), true);
            } else {
                $res = false;
            }
        } else {
            $res = json_decode($res, true);
        }

        return $res;
    }

    //获取fasin代号下单数量
    public function getFasinOrderPlace($fasin_code,$order_time){
        $list = db::table('amazon_place_order_task as a')->leftjoin('amazon_place_order_detail as b','a.id','=','b.order_id')->where('a.status','>=',2)->where('b.fasin_code',$fasin_code)->where('a.creattime','like','%'.$order_time.'%')->get();
        $total = 0;
        foreach ($list as $v) {
            # code...
            $num = array_sum(json_decode($v->order_num));
            $total+=$num;
        }

        return ['total'=> $total,'data'=>$list];
    }
    //根据ID获取品类
    public function GetCategory($id)
    {
        $res = Redis::Hget('datacache:self_category', $id);
        
        if (!$res) {
            $res = Db::table('self_category')->where('Id', $id)->first();
            if (!empty($res)) {
                Redis::Hset('datacache:self_category', $id, json_encode($res));
                $res = json_decode(json_encode($res), true);
            } else {
                $res['name'] = '';
            }
        } else {
            $res = json_decode($res, true);
        }


        return $res;
    }

    //根据ID获取spu
    public function GetSpu($id)
    {
        $res = Redis::Hget('datacache:self_spu', $id);
        if (!$res) {
            $res = Db::table('self_spu')->where('id', $id)->first();
            if ($res) {
                Redis::Hset('datacache:self_spu', $id, json_encode($res));
                $res = json_decode(json_encode($res), true);
            } else {
                $res = false;
            }
        } else {
            $res = json_decode($res, true);
        }

        return $res;
    }


    //根据customsku查找customsku详情
    public function GetCustomSkus($sku)
    {
        $res = Redis::Hget('datacache:self_custom_sku', $sku);
        if (!$res) {
            $res = Db::table('self_custom_sku')->where('custom_sku', $sku)->orWhere('old_custom_sku', $sku)->first();
            // var_dump($res);exit;
            if ($res) {
                Redis::Hset('datacache:self_custom_sku', $sku, json_encode($res));
                $res = json_decode(json_encode($res), true);
            } else {
                $res = false;
            }
        } else {
            $res = json_decode($res, true);
        }

        return $res;
    }


    //补货库存sku
    public function getBuhuoByCus($custom_sku)
    {
        $data['custom_sku'] = $custom_sku;

        //渠道sku子成员N  fnsku(放空)  库存sku   图片 中文名  同安仓库存  预减后同安仓库存  云仓库存 预减后云仓库存 泉州仓库存  预减后泉州仓库存  其余字段放空
        $data['img'] = $this->GetCustomskuImg($custom_sku);
        $cuss = Db::table('self_custom_sku')->where('custom_sku', $custom_sku)->orWhere('old_custom_sku', $custom_sku)->first();
        // $custom_skus[] = $custom_sku;
        // if($cuss->old_custom_sku){
        //     $custom_skus[] = $cuss->old_custom_sku;
        // }
        if (!empty($cuss)) {
            $data['id'] = $cuss->id;
            $data['spu'] = $cuss->spu;
            $data['product_name'] = $cuss->name;
            $saihe_inventory = DB::table('saihe_inventory')
                ->select('good_num', 'warehouse_id', 'client_sku')
                ->where('custom_sku_id', $cuss->id)
                ->whereIn('warehouse_id', [2, 386, 560])
                ->get();
            $data['tongAn_inventory'] = 0;
            $data['quanzhou_inventory'] = 0;
            $data['self_delivery_inventory'] = 0;
            foreach ($saihe_inventory as $inven) {
                //同安仓库存
                if ($inven->warehouse_id == 2) {
                    $data['tongAn_inventory'] += $inven->good_num;
                }
                //同安自发仓
                if ($inven->warehouse_id == 386) {
                    $data['self_delivery_inventory'] += $inven->good_num;
                }

                //泉州仓库存
                if ($inven->warehouse_id == 560) {
                    $data['quanzhou_inventory'] = $inven->good_num;
                }
            }
            //云仓库存
            $data['cloud_inventory'] = $cuss->cloud_num;

            //计划发货
            //补货计划中的发货量
            $plan_num = DB::table('amazon_buhuo_detail as a')
                ->leftJoin('amazon_buhuo_request as b', 'a.request_id', '=', 'b.id')
                ->select('a.sku', 'b.warehouse', 'a.custom_sku', 'a.request_num', 'a.transportation_mode_name')
                ->whereIn('b.request_status', [3, 4, 5, 6, 7])
                ->where('a.custom_sku_id', $cuss->id)
                ->get();

            $data['tongAn_plan'] = 0;
            $data['quanzhou_plan'] = 0;
            $data['cloud_plan'] = 0;
            foreach ($plan_num as $plan) {
                if ($plan->warehouse == 1) {
                    //同安
                    $data['tongAn_plan'] = $plan->request_num;
                }
                if ($plan->warehouse == 2) {
                    //泉州
                    $data['quanzhou_plan'] = $plan->request_num;
                }
                if ($plan->warehouse == 3) {
                    //云仓
                    $data['cloud_plan'] = $plan->request_num;
                }
            }

            //预减
            $data['tongAn_deduct_inventory'] = $data['self_delivery_inventory'] + $data['tongAn_inventory'] - $data['tongAn_plan'];
            $data['quanzhou_deduct_inventory'] = $data['quanzhou_inventory'] - $data['quanzhou_plan'];
            $data['cloud_deduct_inventory'] = $data['cloud_inventory'] - $data['cloud_plan'];

            return $data;
        } else {
            return '';
        }
    }

    //补货库存sku
    public function getBuhuoByCusB($custom_sku)
    {
        $data['custom_sku'] = $custom_sku;

        //渠道sku子成员N  fnsku(放空)  库存sku   图片 中文名  同安仓库存  预减后同安仓库存  云仓库存 预减后云仓库存 泉州仓库存  预减后泉州仓库存  其余字段放空
        $data['img'] = $this->GetCustomskuImg($custom_sku);
        $cuss = Db::table('self_custom_sku')->where('custom_sku', $custom_sku)->orWhere('old_custom_sku', $custom_sku)->first();
        // $custom_skus[] = $custom_sku;
        // if($cuss->old_custom_sku){
        //     $custom_skus[] = $cuss->old_custom_sku;
        // }
        if (!empty($cuss)) {
            $data['id'] = $cuss->id;
            $data['spu'] = $cuss->spu;
            $data['spu_id'] = $cuss->spu_id;
            $data['product_name'] = $cuss->name;
            //同安仓库存
            $data['tongAn_inventory'] = $cuss->tongan_inventory;
            //泉州仓库存
            $data['quanzhou_inventory'] = $cuss->quanzhou_inventory;
            //云仓库存
            $data['cloud_inventory'] = $cuss->cloud_num;
            //寄存仓库存
            $data['deposit_inventory'] = $cuss->deposit_inventory;

            //计划发货
            //补货计划中的发货量
            $plan_num = $this->lock_inventory($cuss->id);

            $data['tongAn_plan'] = 0;
            $data['quanzhou_plan'] = 0;
            $data['cloud_plan'] = 0;
            if ($plan_num) {
                if (isset($plan_num[$cuss->id][1])) {
                    //同安
                    $data['tongAn_plan'] = $plan_num[$cuss->id][1];
                }
                if (isset($plan_num[$cuss->id][2])) {
                    //泉州
                    $data['quanzhou_plan'] = $plan_num[$cuss->id][2];
                }
                if (isset($plan_num[$cuss->id][3])) {
                    //云仓
                    $data['cloud_plan'] = $plan_num[$cuss->id][3];
                }
            }


            //预减
            $data['tongAn_deduct_inventory'] = $data['tongAn_inventory'] - $data['tongAn_plan'];
            $data['quanzhou_deduct_inventory'] = $data['quanzhou_inventory'] - $data['quanzhou_plan'];
            $data['cloud_deduct_inventory'] = $data['cloud_inventory'] - $data['cloud_plan'];

            return $data;
        } else {
            return '';
        }
    }


    public function GetGroupCustomSku($sku)
    {
        $res = Redis::Hget('datacache:self_group_custom_sku', $sku);
        if (!$res) {
            $custom_sku_id = $this->GetCustomSkuId($sku);
            $res = Db::table('self_group_custom_sku')->where('custom_sku_id', $custom_sku_id)->get();
            // var_dump($res);exit;
            if ($res) {
                foreach ($res as $v) {
                    # code...
                    $old = $this->GetOldCustomSku($v->group_custom_sku);
                    if ($old) {
                        $v->group_custom_sku = $old;
                    }
                }

                Redis::Hset('datacache:self_group_custom_sku', $sku, json_encode($res));
                $res = json_decode(json_encode($res), true);
            } else {
                $res = false;
            }
        } else {
            $res = json_decode($res, true);
        }

        return $res;
    }

    //获取组合库存sku最小库存
    public function GetGroupCustomSkuMinInventory($sku)
    {
        $custom_sku_id = $this->GetCustomSkuId($sku);
        $res = Db::table('self_group_custom_sku')->where('custom_sku_id', $custom_sku_id)->get()->toArray();
        $return['tongan_num'] = 0;
        $return['quanzhou_num'] = 0;
        $return['cloud_num'] = 0;

        if ($res) {
            $ids = array_column($res, 'group_custom_sku_id');
            $gres = db::table('self_custom_sku')->whereIn('id', $ids)->get();

            $invens = [];
            // var_dump($gres);
            foreach ($gres as $v) {
                # code...
                $invens['cloud'][] = $v->cloud_num;
                $here = $this->GetSaiheInventory($v->id);
                $invens['quanzhou'][] = $here['quanzhou'];
                $invens['tongan'][] = $here['tongan'];
            }

            var_dump($invens);

            // $clouds = array_column($invens,'cloud');
            // $quanzhous = array_column($invens,'quanzhous');
            // $tongans = array_column($invens,'tongans');

            // var_dump($tongans);
            $return['tongan_num'] = min($invens['tongan']);
            $return['quanzhou_num'] = min($invens['quanzhou']);
            $return['cloud_num'] = min($invens['cloud']);
            // var_dump($return['tongan_num']);

        }

        // var_dump( $return);
        return $return;
    }

    //获取组合库存sku最小库存
    public function GetGroupCustomSkuMinInventoryB($sku,$platform_id)
    {
        $custom_sku_id = $this->GetCustomSkuId($sku);
        $res = Db::table('self_group_custom_sku')->where('custom_sku_id', $custom_sku_id)->get()->toArray();
        //   var_dump($res);
        $return['tongan_num'] = 0;
        $return['quanzhou_num'] = 0;
        $return['cloud_num'] = 0;

        if ($res) {
            $ids = array_column($res, 'group_custom_sku_id');
            $gres = db::table('self_custom_sku')->whereIn('id', $ids)->get();

            $invens = [];

            $requestres = $this->lock_inventory($ids,5);

            //[1=>同安仓 2.泉州仓 3.云仓 6.工厂寄存仓]


            // var_dump($gres);
            $i = 0;
            foreach ($gres as $v) {
                # code...

                $invens['cloud'][$i] = $v->cloud_num;
                $invens['quanzhou'][$i] = $v->quanzhou_inventory;
                $invens['tongan'][$i] = $v->tongan_inventory;
                $invens['deposit'][$i] = $v->deposit_inventory;

                if (isset($requestres[$v->id][1])) {
                    $invens['tongan'][$i] = $v->tongan_inventory - $requestres[$v->id][1];
                }
                if (isset($requestres[$v->id][2])) {
                    $invens['quanzhou'][$i] = $v->quanzhou_inventory - $requestres[$v->id][2];
                }
                if (isset($requestres[$v->id][3])) {
                    $invens['cloud'][$i] = $v->cloud_num - $requestres[$v->id][3];
                }
                if (isset($requestres[$v->id][6])) {
                    $invens['deposit'][$i] = $v->deposit_inventory - $requestres[$v->id][6];
                }
                $i++;

            }


            // $clouds = array_column($invens,'cloud');
            // $quanzhous = array_column($invens,'quanzhous');
            // $tongans = array_column($invens,'tongans');

            // var_dump($tongans);
            $return['tongan_num'] = min($invens['tongan']);
            $return['quanzhou_num'] = min($invens['quanzhou']);
            $return['cloud_num'] = min($invens['cloud']);
            $return['deposit_num'] = min($invens['deposit']);
            // var_dump($return['tongan_num']);

        }

        // var_dump( $return);
        return $return;
    }

    public function GetSaiheInventory($custom_sku_id)
    {
        //赛盒库存start
        $saihe_inventory = Db::table('saihe_inventory')->where('custom_sku_id', $custom_sku_id)->get();

        //   var_dump( $saihe_inventory);
        $return['tongan'] = 0;
        $return['quanzhou'] = 0;
        $saihe_res = [];
        $saihe_res['tongan'] = 0;
        $saihe_res['quanzhou'] = 0;
        if ($saihe_inventory) {
            foreach ($saihe_inventory as $v) {
                # code...
                if ($v->warehouse_id == 2 || $v->warehouse_id == 386) {
                    $saihe_res['tongan'] += $v->good_num;
                }
                if ($v->warehouse_id == 560) {
                    $saihe_res['quanzhou'] += $v->good_num;
                }
            }
            $return['tongan'] = $saihe_res['tongan'];
            $return['quanzhou'] = $saihe_res['quanzhou'];
        }


        // if($saihe_inventory->warehouse_id==2||$saihe_inventory->warehouse_id==386){
        //     $return['tongan'] =  $saihe_inventory->good_num;
        // }
        // if($saihe_inventory->warehouse_id==560){
        //     $return['quanzhou'] =  $saihe_inventory->good_num;
        // }


        //   var_dump($custom_sku_id);
        //   var_dump($return);
        return $return;
    }

    public function GetGroupSpu($spu)
    {
        $res = Redis::Hget('datacache:self_group_spu', $spu);
        if (!$res) {
            $spu_id = $this->GetSpuId($spu);
            $res = Db::table('self_group_spu')->where('spu_id', $spu_id)->get();
            // var_dump($res);exit;
            if ($res) {
                foreach ($res as $v) {
                    # code...
                    $old = $this->GetOldSpu($v->spu);
                    if ($old != $v->spu) {
                        $v->group_spu = $old;
                    }
                }

                Redis::Hset('datacache:self_group_spu', $spu, json_encode($res));
                $res = json_decode(json_encode($res), true);
            } else {
                $res = false;
            }
        } else {
            $res = json_decode($res, true);
        }

        return $res;
    }

    //根据sku查找sku详情
    public function GetSku($sku)
    {
        $res = Redis::Hget('datacache:self_sku', $sku);
        if (!$res) {
            $res = Db::table('self_sku')->where('sku', $sku)->orWhere('old_sku', $sku)->first();
            if ($res) {
                Redis::Hset('datacache:self_sku', $sku, json_encode($res));
                $res = json_decode(json_encode($res), true);
            } else {
                $res = false;
            }
        } else {
            $res = json_decode($res, true);
        }

        return $res;
    }

    //获取绑定后的新sku
    public function GetNewSku($sku)
    {
        $newsku = Redis::Hget('datacache:new_sku', $sku);
        if (!$newsku) {
            $res = Db::table('self_sku')->where('sku', $sku)->orwhere('old_sku', $sku)->first();
            if ($res) {
                $newsku = $res->sku;
                Redis::Hset('datacache:new_sku', $sku, $newsku);
            } else {
                $newsku = false;
            }
        }
        return $newsku;
    }

    //获取绑定后的旧sku
    public function GetOldSku($sku)
    {
        $oldsku = Redis::Hget('datacache:old_sku', $sku);
        if (!$oldsku) {
            $res = Db::table('self_sku')->where('sku', $sku)->orwhere('old_sku', $sku)->first();

            if ($res) {
                if (!empty($res->old_sku)) {
                    $oldsku = $res->old_sku;
                    Redis::Hset('datacache:old_sku', $sku, $oldsku);
                } else {
                    $oldsku = false;
                }

            } else {
                $oldsku = false;
            }
        }
        return $oldsku;
    }

    //获取绑定后的新custom_sku
    public function GetNewCustomSku($custom_sku)
    {
        $newcustomsku = Redis::Hget('datacache:new_customsku', $custom_sku);
        if (!$newcustomsku) {
            $res = Db::table('self_custom_sku')->where('custom_sku', $custom_sku)->orwhere('old_custom_sku', $custom_sku)->first();
            if ($res) {
                $newcustomsku = $res->custom_sku;
                Redis::Hset('datacache:new_customsku', $custom_sku, $newcustomsku);
            } else {
                $newcustomsku = false;
            }
        }
        return $newcustomsku;
    }

    //获取绑定后的旧custom_sku
    public function GetOldCustomSku($custom_sku)
    {
        $oldcustomsku = Redis::Hget('datacache:old_customsku', $custom_sku);
        if (!$oldcustomsku) {
            $res = Db::table('self_custom_sku')->where('custom_sku', $custom_sku)->orwhere('old_custom_sku', $custom_sku)->first();
            if (!empty($res)) {
                if ($res->old_custom_sku) {
                    $oldcustomsku = $res->old_custom_sku;
                    Redis::Hset('datacache:old_customsku', $custom_sku, $oldcustomsku);
                } else {
                    $oldcustomsku = false;
                }
            } else {
                $oldcustomsku = false;
            }
//            var_dump($custom_sku);
//            var_dump($res);

        }
        return $oldcustomsku;
    }

    //获取绑定后的新spu
    public function GetNewSpu($spu)
    {
        $newspu = Redis::Hget('datacache:new_spu', $spu);
        if (!$newspu) {
            $res = Db::table('self_spu')->where('spu', $spu)->orwhere('old_spu', $spu)->first();
            if ($res) {
                $newspu = $res->spu;
                Redis::Hset('datacache:new_spu', $spu, $newspu);
            } else {
                $newspu = false;
            }
        }
        return $newspu;
    }


    //获取旧spu 无则新
    public function GetOldSpu($spu)
    {
        $oldspu = Redis::Hget('datacache:old_spu', $spu);
        if (!$oldspu) {
            $res = Db::table('self_spu')->where('spu', $spu)->orwhere('old_spu', $spu)->first();
            if (!empty($res)) {
                if ($res->old_spu) {
                    $oldspu = $res->old_spu;
                } else {
                    $oldspu = $res->spu;
                }
                Redis::Hset('datacache:old_spu', $spu, $oldspu);
            } else {
                return $spu;
            }
        }
        return $oldspu;
    }

    public function GetSpuImg($spu)
    {
        $img = Redis::Hget('datacache:spu_imgs', $spu);
        if (!$img) {
            $base_spu_id = $this->GetBaseSpuIdBySpu($spu);
            $res = Db::table('self_spu_color')->where('base_spu_id', $base_spu_id)->where('img', '!=', '')->first();
            if (!empty($res->img)) {
                $img = $res->img;
                Redis::Hset('datacache:spu_imgs', $spu, $img);
            } else {
                $img = '';
            }
        }
        return $img;
    }


    //根据库存sku读取成本价
    public function GetCustomSkuPrice($custom_sku)
    {
        $price = 0;
        $test_cus_price = db::table('cus_price_test')->where('custom_sku', $custom_sku)->first();
        if ($test_cus_price) {
            $price = $test_cus_price->price;
            return $price;
        }
        $cus = $this->GetCustomSkus($custom_sku);
        if ($cus) {
            $base_spu_id = $this->GetBaseSpuIdBySpu($cus['spu']);
            if ($base_spu_id > 0) {
                $base = db::table('self_spu_color')->where('base_spu_id', $base_spu_id)->where('color_id', $cus['color_id'])->first();
                if ($base) {
                    $price = $base->price;
                }
            }
        }
        return $price;
    }

    //根据库存sku修改成本价
    public function UpdateCustomSkuPrice($custom_sku, $price)
    {
        $cus = $this->GetCustomSkus($custom_sku);
        if ($cus) {
            $base_spu_id = $this->GetBaseSpuIdBySpu($cus['spu']);
            if ($base_spu_id > 0) {
                db::table('self_spu_color')->where('base_spu_id', $base_spu_id)->where('color_id', $cus['color_id'])->update(['price' => $price]);
            }
        }
        return true;
    }


    public function GetBaseSpuImg($id)
    {
        // $img = Redis::Hget('datacache:base_spu_img',$id);

        $res = Db::table('self_spu_color')->where('base_spu_id', $id)->where('img', '!=', '')->first();
        if ($res) {
            $img = '';
            if (!empty($res->img)) {
                $img = $res->img;
                // Redis::Hset('datacache:base_spu_img',$id,$img);
            }
        } else {
            $img = '';
        }

        return $img;
    }


    //出库加权价格查询
    public function GetCloudHousePrice($warehouse_id, $custom_sku_id)
    {
        $res = Db::table('inventory_total_pirce')->where('warehouse_id', $warehouse_id)->where('custom_sku_id', $custom_sku_id)->first();
        $price = 0;
        if ($res) {
            if ($res->price <= 0) {
                $price = 0;
            } else {
                if($res->num<=0){
                    $price = 0;
                }else{
                    $price = round($res->price / $res->num, 2);                }
            }
        }
        return $price;
    }


    //出库加权价格增加
    public function UpCloudHousePrice($params)
    {

        $warehouse_id = $params['warehouse_id'];
        $custom_sku_id = $params['custom_sku_id'];
        $price = $params['price'];
        $num = $params['num'];
        $user_id = $params['user_id'];
        $type = $params['type'] ?? 1;  //1为出 2为入
        $res = Db::table('inventory_total_pirce')->where('warehouse_id', $warehouse_id)->where('custom_sku_id', $custom_sku_id)->first();
        $cus = db::table('self_custom_sku')->where('id', $custom_sku_id)->first();
        //查询仓库当前总资产
        $warehouse_price = db::table("cloudhouse_warehouse")->where('id', $warehouse_id)->select('total_price')->first();

        $spu_id = 0;
        $spu = '';
        $custom_sku = '';
        if ($cus) {
            $spu_id = $cus->spu_id;
            $spu = $cus->spu;
            $custom_sku = $cus->custom_sku;
        }
        if (!empty($res)) {
            if ($type == 1) {
//                if($price>$res->price||$num>$res->num){
//                    return['type'=>'fail','msg'=>"价格或数量为0"];
//                }
                $update['price'] = $res->price - $price * $num;
                $update['num'] = $res->num - $num;
                $balance = $warehouse_price->total_price - $price * $num;
            } elseif ($type == 2) {
                $update['price'] = $res->price + $price * $num;
                $update['num'] = $res->num + $num;
                $balance = $warehouse_price->total_price + $price * $num;
            }

            Db::table('inventory_total_pirce')->where('id', $res->id)->update($update);
        } else {
            if ($type == 1) {
                $balance = 0;
//                return['type'=>'fail','msg'=>"无入库数据"];
            }
            if ($type == 2) {
                $insert['price'] = $price * $num;
                $insert['warehouse_id'] = $warehouse_id;
                $insert['custom_sku_id'] = $custom_sku_id;
                $insert['num'] = $num;
                $insert['spu_id'] = $spu_id;
                $insert['spu'] = $spu;
                $insert['custom_sku'] = $custom_sku;
                db::table("inventory_total_pirce")->insert($insert);
                $balance = $warehouse_price->total_price + $price * $num;
            }
        }
//        print_r($balance.'---');
        //修改总资产
        db::table("cloudhouse_warehouse")->where('id', $warehouse_id)->update(['total_price' => $balance]);
        $loginsert['custom_sku_id'] = $custom_sku_id;
        $loginsert['type'] = $type;
        $loginsert['user_id'] = $user_id;
        $loginsert['price'] = $price;
        $loginsert['num'] = $num;
        $loginsert['update_time'] = date('Y-m-d H:i:s', time());
        Db::table('inventory_total_pirce_log')->insert($loginsert);
        return ['type' => 'success', 'msg' => "修改成功", 'total_price' => $balance];
    }


    public function GetCustomskuImg($custom_sku)
    {
        $imgs = Redis::Hget('datacache:customsku_img', $custom_sku);

        if (!$imgs) {
            // echo '2'.$custom_sku;
            $custom_skus = $this->GetCustomSkus($custom_sku);

            if (isset($custom_skus['spu']) && isset($custom_skus['color_id'])) {
                // $base_spu = db::table('self_spu')->where('id', $custom_skus['spu_id'])->first();
                // if(!$base_spu){
                //     $img = '';
                //     return $img;
                // }
                // $base_spu_id = $base_spu->base_spu_id;
                $res = Db::table('self_spu_color')->where('base_spu_id', $custom_skus['spu_id'])->where('color_id', $custom_skus['color_id'])->first();
                if ($res) {
                    $img = $res->img;
                    if ($res->img) {
                        // Redis::Hset('datacache:customsku_img',$custom_sku,$img);
                        // if($custom_sku=='CFMWY00014-Black-2XL'){
                        $data['spu'] = $custom_skus['spu'];
                        $data['color_id'] = $custom_skus['color_id'];
                        $data['base_spu_id'] = $custom_skus['spu_id'];
                        $data['img'] = $img;
                        Redis::Hset('datacache:customsku_img', $custom_sku, json_encode($data));

                    }
                } else {
                    $img = '';
                }
            } else {
                $img = '';
            }
            // var_dump(  $custom_skus);
            // $color = Db::table('self_color_size')->where('id',$custom_skus['color_id'])->first();

        } else {
            $img = json_decode($imgs, true)['img'];
        }
        return $img;
    }


    //获取基础spuID
    public function GetBaseSpuIdBySpu($spu)
    {
        $id = Redis::Hget('datacache:base_spu_id', $spu);
        if (!$id) {
            $res = Db::table('self_spu')->where('spu', $spu)->orwhere('old_spu', $spu)->first();
            if ($res) {
                Redis::Hset('datacache:base_spu_id', $spu, $res->id);
                $id = $res->id;
            }
        }
        return $id;
    }


    //获取spuID
    public function GetSpuId($spu)
    {
        $id = Redis::Hget('datacache:spu_id', $spu);
        if (!$id) {
            $res = Db::table('self_spu')->where('spu', $spu)->orwhere('old_spu', $spu)->first();
            if ($res) {
                Redis::Hset('datacache:spu_id', $spu, $res->id);
                $id = $res->id;
            } else {
                $id = 0;
            }
        }
        return $id;
    }


    //获取custom_skuID
    public function GetCustomSkuId($custom_sku)
    {
        $id = 0;
        $id = Redis::Hget('datacache:custom_sku_id', $custom_sku);
        if (!$id) {
            $res = Db::table('self_custom_sku')->where('custom_sku', $custom_sku)->orwhere('old_custom_sku', $custom_sku)->first();
            if ($res) {
                Redis::Hset('datacache:custom_sku_id', $custom_sku, $res->id);
                $id = $res->id;
            }
        }
        return $id;
    }

    //获取skuID
    public function GetSkuId($sku)
    {
        $id = Redis::Hget('datacache:sku_id', $sku);
        if (!$id) {
            $res = Db::table('self_sku')->where('sku', $sku)->orwhere('old_sku', $sku)->first();
            if ($res) {
                Redis::Hset('datacache:sku_id', $sku, $res->id);
                $id = $res->id;
            }
        }
        return $id;
    }

    //获取新旧spu
    public function GetSpus($spu)
    {
        $newspu = Redis::Hget('datacache:newoldspu', $spu);
        if (!$newspu) {
            $res = Db::table('self_spu')->where('spu', $spu)->orwhere('old_spu', $spu)->first();
            if ($res) {
                $newspu[0] = $res->spu;
                if ($res->old_spu) {
                    $newspu[1] = $res->old_spu;
                }
                Redis::Hset('datacache:newoldspu', $spu, json_encode($newspu));
            } else {
                $newspu = false;
            }
        } else {
            $newspu = json_decode($newspu, true);
        }
        return $newspu;
    }

    //根据id获取补货计划状态
    public function GetPlan($id)
    {
        $res = Redis::Hget('datacache:plan_status', $id);
        if (!$res) {
            $res = Db::table('amazon_plan_status')->where('id', $id)->first();
            if ($res) {
                Redis::Hset('datacache:plan_status', $id, json_encode($res));
                $res = json_decode(json_encode($res), true);
            } else {
                $res = false;
            }
        } else {
            $res = json_decode($res, true);
        }

        return $res;
    }

    public function taskSend($user_id, $content)
    {
        $user_mb = DB::table('users')->where('Id', $user_id)->select()->first();
        $mobile = array();
        if (!empty($user_mb->assistant)) {
            if (strpos($user_mb->assistant, ',')) {
                $assistant = explode(",", $user_mb->assistant);
                foreach ($assistant as $ass) {
                    $user_ass = DB::table('users')->where('Id', $ass)->select('phone')->first();
                    $mobile[] = $user_ass->phone;
                }
            } else {
                $user_ass = DB::table('users')->where('Id', $user_mb->assistant)->select('phone')->first();
                $mobile[] = $user_ass->phone;
            }
        } else {
            $mobile[] = $user_mb->phone ?? '';
        }
        $this->DingdingSend($content, $mobile);
    }

    public function msgSend($user_list, $content)
    {
        $user_mb = DB::table('users')->whereIn('Id', $user_list)->select('phone')->get();
        $user_mb = json_decode(json_encode($user_mb), true);
        if (!empty($user_mb)) {
            $phone = array_column($user_mb, 'phone');
            $this->DingdingSend($content, $phone);
        }
    }

    public function DingdingSend($message, $phone)
    {

        $webhook = "https://oapi.dingtalk.com/robot/send?access_token=99dc5f66709508cc4ff6ec0e4bc12e3c455dc4e099bc59c0bd410a3e2ead1f93";

        $data = array('msgtype' => 'text', 'text' => array('content' => $message), 'at' => array('atMobiles' => $phone));
        $data_string = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $webhook);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); 
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    public function warehouseSend($message, $user_list)
    {

        $user_mb = DB::table('users')->whereIn('Id', $user_list)->select('phone')->get();
        $user_mb = json_decode(json_encode($user_mb), true);
        if (!empty($user_mb)) {
            $phone = array_column($user_mb, 'phone');
        }

        $webhook = "https://oapi.dingtalk.com/robot/send?access_token=acac616d098e566980a8e3736d2bdd7f8973fcc706b016d4cbc53d49149fc044";

        $data = array('msgtype' => 'text', 'text' => array('content' => $message), 'at' => array('atMobiles' => $phone));
        $data_string = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $webhook);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }


    //根据id获取库位信息
    public function Getlocation($id)
    {
        $res = Redis::Hget('datacache:location', $id);
        if (!$res) {
            $res = Db::table('cloudhouse_warehouse_location')->where('id', $id)->first();
            if ($res) {
                Redis::Hset('datacache:location', $id, json_encode($res));
                $res = json_decode(json_encode($res), true);
            } else {
                $res = false;
            }
        } else {
            $res = json_decode($res, true);
        }

        return $res;
    }

    //锁定库存并将出库分配数据存入中转任务箱
//    public function PointsLocation($custom_sku_id, $warehouse, $num, $box_id, $custom_sku, $platform_id)
//    {
//        $params['token'] = 'F0398D14F1F76ECC675A2C292E53A367';
//        $params['custom_sku_id'] = $custom_sku_id;
//        $params['warehouse'] = $warehouse;
//        $params['num'] = $num;
//        $params['box_id'] = $box_id;
//        $params['custom_sku'] = $custom_sku;
//        $params['platform_id'] = $platform_id;
//
//
//        $this->AddSysLog($params, '', '锁定库存', __METHOD__);
//
//        $data = DB::table('cloudhouse_location_num as a')->leftJoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
//            ->where('custom_sku_id', $custom_sku_id)->where('warehouse_id', $warehouse)->where('a.num', '!=', 'a.lock_num')->where('a.num', '>', 0);
////        if($platform_id!=0){
////            $data = $data->where('b.platform_id',$platform_id);
////        }
//        $data = $data->select('a.id', 'a.custom_sku_id', 'a.num', 'a.lock_num', 'a.location_id', 'b.level', 'b.sort')
//            ->orderBy('b.sort', 'asc')
//            ->orderBy('b.sort2', 'asc')
//            ->orderBy('b.sort3', 'asc')
//            ->get();
//
//        if (!$data->isEmpty()) {
//            $arr = array();
//            $locationIdArr = array();//库位id=>取出库存
//            $instock_total_num = 0;
//            foreach ($data as $dt) {
//                $instock_total_num += ($dt->num - $dt->lock_num);
//                $arr[] = ['id' => $dt->id, 'location_id' => $dt->location_id, 'instock_num' => $dt->num - $dt->lock_num, 'num' => $dt->num, 'lock_num' => $dt->lock_num];
//            }
//            if ($instock_total_num < $num) {
//                return '库存skuid' . $custom_sku_id . '仓库:' . $warehouse . '平台：' . $platform_id . '补货数量/库存' . $num . '/' . $instock_total_num . '可用库存不足-101';
//            }
//            $this_now_num = $num;
//            $i = 0;
//            do {
//                $this_now_num -= $arr[$i]['instock_num'];
//                if ($this_now_num > 0) {
//                    $locationIdArr[$arr[$i]['location_id']] = $arr[$i]['instock_num'];
//                    $update['lock_num'] = $arr[$i]['num'];
//                } else {
//                    $locationIdArr[$arr[$i]['location_id']] = $this_now_num + $arr[$i]['instock_num'];
//                    $update['lock_num'] = $this_now_num + $arr[$i]['instock_num'] + $arr[$i]['lock_num'];
//                }
//                //修改已锁定库存
//                DB::table('cloudhouse_location_num')->where('id', $arr[$i]['id'])->update($update);
//                $i++;
//            } while ($this_now_num > 0);
//
//            foreach ($locationIdArr as $key => $value) {
//                $total_sku_num = DB::table('goods_transfers_box_detail')->where('box_id', $box_id)->where('custom_sku_id', $custom_sku_id)->sum('box_num');
//                if ($total_sku_num) {
//                    $now_total_num = $total_sku_num + $value;
//                    if ($instock_total_num < $now_total_num) {
//                        return '库存' . $custom_sku . '仓库:' . $warehouse . '平台：' . $platform_id . '可用库存不足,请检查是否组合sku的子sku发货量超出可用库存';
//                    }
//                }
//                DB::table('goods_transfers_box_detail')->insert([
//                    'box_id' => $box_id,
//                    'custom_sku' => $custom_sku,
//                    'custom_sku_id' => $custom_sku_id,
//                    'box_num' => $value,
//                    'location_ids' => $key
//                ]);
//            }
//            $goods_transfers_box = DB::table('goods_transfers_box')->where('id', $box_id)->select('box_num')->first();
//            if (!empty($goods_transfers_box)) {
//                $updateNum = $goods_transfers_box->box_num + $num;
//            } else {
//                $updateNum = $num;
//            }
//            DB::table('goods_transfers_box')->where('id', $box_id)->update(['box_num' => $updateNum]);
//            $log['custom_sku_id'] = $custom_sku_id;
//            $log['warehouse'] = $warehouse;
//            $log['num'] = $num;
//            $log['box_id'] = $box_id;
//            $log['custom_sku'] = $custom_sku;
//            $log['platform_id'] = $platform_id;
//            $log['create_time'] = date('Y-m-d H:i:s', time());
//            db::table('lock_inventory_log')->insert($log);
//            return 1;
//        } else {
//            return '没有此产品的库位库存数据';
//        }
//
//    }


    //验证锁定库存
    public function CheckPointsLocation($custom_sku_id, $warehouse, $num, $box_id, $custom_sku,$platform_id,$type_detail,$type)
    {

        //同一订单内如果有相同库存sku则验证数量-累加

        $rnum = 0;
        $rnum = Redis::get('location_lock:'.$custom_sku_id.$warehouse.$box_id);
        $num += $rnum;


        Redis::setex('location_lock:'.$custom_sku_id.$warehouse.$box_id,60,$num);

//        DB::enableQueryLog();

        $locationData = DB::table('cloudhouse_location_num as a')
            ->leftJoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
            ->where('a.custom_sku_id', $custom_sku_id)
            ->where('b.warehouse_id', $warehouse)
            ->where('b.type',$type);
        $platform_data = $this->GetPlatform($platform_id);//获取平台信息
        $warehouse_data = $this->GetWarehouse($warehouse);//获取仓库信息
        if($warehouse_data){
            $warehouse_name = $warehouse_data['warehouse_name'];
        }else{
            $warehouse_name = '';
        }
        $platform_name = '';


        if($type_detail!=15){
            if($platform_id==13){
                if($warehouse==1){
                    $locationData =  $locationData->where('b.id','!=',1467);
                }
                if($warehouse==2){
                    $locationData =  $locationData->where('b.id','!=',3159);
                }
            }
//            if($platform_data){
                $locationData =  $locationData->where('a.platform_id',$platform_id);
                $platform_name = $platform_data['name'];
//            }else{
//                $locationData =  $locationData->where('b.fid','!=',341)->where('b.fid','!=',3127);
//            }
        }else{
            $locationData =  $locationData->where('a.platform_id',$platform_id)->whereNotIn('b.fid',[341,343,344,3127,3129,3130]);
        }

        $locationData =  $locationData->select('a.id', 'a.custom_sku_id', 'a.num', 'a.location_id', 'b.level', 'b.sort')
            ->orderBy('a.num', 'desc')
            ->get();
       
//        \Illuminate\Support\Facades\Log::debug(var_export(DB::getQueryLog(), true));

        $locationNum = array();
        $locationIds = array();
        if(!$locationData->isEmpty()) {
            foreach ($locationData as $ll) {
                if ($ll->num > 0) {
                    $locationIds[] = $ll->location_id;
                    $locationNum[$ll->location_id] = $ll->num;
                }
            }
        }else {
            return '没有此产品的库位库存数据库存sku'.$custom_sku.'--custom_sku_id:'.$custom_sku_id.'仓库：'.$warehouse.'--平台：'.$platform_name.'--箱号：'.$box_id.'库位号'.json_encode($locationIds);
        }



        $data = DB::table('goods_transfers_box_detail as a')
            ->leftJoin('goods_transfers_box as b', 'a.box_id', '=', 'b.id')
            ->leftJoin('goods_transfers as c', 'b.order_no', '=', 'c.order_no')
            ->where('a.custom_sku_id', $custom_sku_id)
            ->where('c.out_house', $warehouse)
            ->where('c.platform_id',$platform_id)
            ->whereIn('a.location_ids', $locationIds)
            ->whereIn('c.type_detail', $this->GetfieldTypeDetail3())
            ->whereIn('c.is_push', [1, 2, 4])
            ->select('a.custom_sku','c.order_no','a.box_num', 'a.shelf_num', 'a.location_ids','b.type')
            ->get();

      
        if (!$data->isEmpty()) {
            foreach ($data as $v) {
                if($v->box_num>0){
                    if (isset($locationNum[$v->location_ids])) {
                        if($v->type==1) {
                            $balance = 0;
                        }
                        if($v->type==2){
                            $balance = $v->box_num - $v->shelf_num;
                        }
                        $locationNum[$v->location_ids] = $locationNum[$v->location_ids] - $balance;
                    }
                }
            }
        }

        $locationSumNum = array_sum($locationNum);
        if ($locationSumNum < $num) {
            return $custom_sku . '在仓库:' . $warehouse . '平台：'.$platform_name. '的可用库存不足，只能出库' . $locationSumNum . '件';
        }
        $locationInstockNum = array();
        foreach ($locationNum as $ck => $cv) {
            //库位锁定库存
            // $l_num = 0;
            // $l_num = Redis::get('location_lock:'.$custom_sku_id.$warehouse.$box_id.'lid:'.$ck);
            // $cv =  $cv-$l_num;
            // Redis::setex('location_lock:'.$custom_sku_id.$warehouse.$box_id.'lid:'.$ck,60,$cv);
            $locationInstockNum[] = ['location_id' => $ck, 'instock_num' => $cv];
        }
    //        if($platform_id!=0){
    //            $data = $data->where('b.platform_id',$platform_id);
    //        }
        $locationIdArr = array();
        $this_now_num = $num;
        $i = 0;
        do {
            $this_now_num -= $locationInstockNum[$i]['instock_num'];
            if ($this_now_num > 0) {
                $locationIdArr[$locationInstockNum[$i]['location_id']] = $locationInstockNum[$i]['instock_num'];
            } else {
                $locationIdArr[$locationInstockNum[$i]['location_id']] = $this_now_num + $locationInstockNum[$i]['instock_num'];
            }
            $i++;
        } while ($this_now_num > 0);

        foreach ($locationIdArr as $key => $value) {

            // DB::connection()->enableQueryLog();
            $total_sku_num = DB::table('goods_transfers_box_detail')->where('box_id', $box_id)->where('custom_sku_id', $custom_sku_id)->sum('box_num');
            // var_dump(DB::getQueryLog());
            // echo $box_id.'/'.$custom_sku_id.'/'. $total_sku_num;
            if ($total_sku_num) {
                $now_total_num = $total_sku_num + $value - $rnum;
                if ($locationSumNum < $now_total_num) {
                    return  $custom_sku . '在仓库:' . $warehouse  . '的可用库存不足，库存量'.$locationSumNum.'总下单量'.$now_total_num.'box_id'.$box_id.'其他下单'.$total_sku_num.',请检查是否组合sku的子sku发货量超出可用库存';
                }
            }
            if($value<0){
                return  $custom_sku . '的库存分配出错:' . $warehouse  . '分配数量:'.$value.'请联系技术人员处理';
            }
        }
        return 1;
    }
    //锁定库存并将出库分配数据存入中转任务箱
    public function PointsLocation($custom_sku_id, $warehouse, $num, $box_id, $custom_sku, $platform_id,$type_detail,$type,$status=1)
    {
        if($status=0){
            return '出库推送功能暂时禁用，预计在下午恢复';
        }
        
        //锁
        $lock = Redis::get('location_lock:'.$custom_sku_id.$warehouse);
        if($lock){
            sleep(5);
//            $custom_sku = db::table('self_custom_sku')
//                ->where('id', $custom_sku_id)
//                ->select('name')
//                ->first();
//            $warehouseName = $this->GetWarehouse($warehouse)['warehouse_name'] ?? '';
//            return "仓库：".$warehouseName.'，CustomSku：'.$custom_sku->name.'存在数据正在操作中，请稍后再进行操作。';
        }
        Redis::setex('location_lock:'.$custom_sku_id.$warehouse,5,1);

        //订单验证
        $check = $this->CheckPointsLocation($custom_sku_id, $warehouse, $num, $box_id, $custom_sku,$platform_id,$type_detail,$type);
        if($check!=1){
            Redis::Del('location_lock:'.$custom_sku_id.$warehouse.$box_id);
            return '校验失败'.$check;
        }

        $locationData = DB::table('cloudhouse_location_num as a')
            ->leftJoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
            ->where('a.custom_sku_id', $custom_sku_id)
            ->where('b.warehouse_id', $warehouse)
            ->where('b.type',$type);
        $platform_data = $this->GetPlatform($platform_id);//获取平台信息
        $warehouse_data = $this->GetWarehouse($warehouse);//获取仓库信息
        if($warehouse_data){
            $warehouse_name = $warehouse_data['warehouse_name'];
        }else{
            $warehouse_name = '';
        }
        $platform_name = '';

        if($type_detail!=15){
            if($platform_id==13){
                if($warehouse==1){
                    $locationData =  $locationData->where('b.id','!=',1467);
                }
                if($warehouse==2){
                    $locationData =  $locationData->where('b.id','!=',3159);
                }
            }
//            if($platform_data){
                $locationData =  $locationData->where('a.platform_id',$platform_id);
                $platform_name = $platform_data['name'];
//            }else{
//                $locationData =  $locationData->where('b.fid','!=',341)->where('b.fid','!=',3151);
//            }
        }else{
            $locationData =  $locationData->where('a.platform_id',$platform_id)->whereNotIn('b.fid',[341,343,344,3151,3155,3159,3163]);
        }

        $locationData =  $locationData->select('a.id', 'a.custom_sku_id', 'a.num', 'a.location_id', 'b.level', 'b.sort','a.platform_id')
            ->orderBy('a.num', 'desc')
            ->get();


        $locationNum = array();
        $locationIds = array();
        if(!$locationData->isEmpty()) {
            foreach ($locationData as $ll) {
                if ($ll->num > 0) {
                    $locationIds[] = $ll->location_id;
                    $locationNum[$ll->location_id] = $ll->num;
                }
            }
        }else {
            return '没有此产品的库位库存数据';
        }



        $data = DB::table('goods_transfers_box_detail as a')
            ->leftJoin('goods_transfers_box as b', 'a.box_id', '=', 'b.id')
            ->leftJoin('goods_transfers as c', 'b.order_no', '=', 'c.order_no')
            ->where('a.custom_sku_id', $custom_sku_id)
            ->where('c.out_house', $warehouse)
            ->where('c.platform_id',$platform_id)
            ->whereIn('a.location_ids', $locationIds)
            ->whereIn('c.type_detail', $this->GetfieldTypeDetail3())
            ->whereIn('c.is_push', [1, 2, 4])
            ->select('a.custom_sku','c.order_no','a.box_num', 'a.shelf_num', 'a.location_ids','b.type')
            ->get();


        if (!$data->isEmpty()) {
            foreach ($data as $v) {
                if($v->box_num>0){
                        if (isset($locationNum[$v->location_ids])) {
                            if($v->type==1) {
                                $balance = 0;
                            }
                            if($v->type==2){
                                $balance = $v->box_num - $v->shelf_num;
                            }

                            $locationNum[$v->location_ids] = $locationNum[$v->location_ids] - $balance;
                        }
                    }
                }
        }

        $locationSumNum = array_sum($locationNum);
        if ($locationSumNum < $num) {
            return $custom_sku . '在仓库:' . $warehouse .'平台：'.$platform_name. '的可用库存不足，只能出库' . $locationSumNum . '件';
        }
        $locationInstockNum = array();
        arsort($locationNum);
        foreach ($locationNum as $ck => $cv) {
            $l_num = 0;
            $l_num = Redis::get('location_lock:'.$custom_sku_id.$warehouse.$box_id.'lid:'.$ck);
            $cv =  $cv-$l_num;
            $locationInstockNum[] = ['location_id' => $ck, 'instock_num' => $cv];
        }
//        if($platform_id!=0){
//            $data = $data->where('b.platform_id',$platform_id);
//        }
        $locationIdArr = array();
        $this_now_num = $num;
        $i = 0;
        do {

            $this_now_num -= $locationInstockNum[$i]['instock_num'];

            $rk_lo_id = $locationInstockNum[$i]['location_id'];

            if ($this_now_num > 0) {
                $locationIdArr[$locationInstockNum[$i]['location_id']] = $locationInstockNum[$i]['instock_num'];
                $rk_lo_num =  $locationInstockNum[$i]['instock_num'];
            } else{
                $locationIdArr[$locationInstockNum[$i]['location_id']] = $this_now_num + $locationInstockNum[$i]['instock_num'];
                $rk_lo_num =   $this_now_num + $locationInstockNum[$i]['instock_num'];
            }

            Redis::setex('location_lock:'.$custom_sku_id.$warehouse.$box_id.'lid:'.$rk_lo_id,60,$rk_lo_num);

            $i++;
        } while ($this_now_num > 0);

        foreach ($locationIdArr as $key => $value) {
            $total_sku_data = DB::table('goods_transfers_box_detail')->where('box_id', $box_id)->where('custom_sku_id', $custom_sku_id)->select('box_num','id','location_ids')->get();
            $total_sku_num = 0;
            $boxLocationArr = [];
            if(!$total_sku_data->isEmpty()){
                foreach ($total_sku_data as $t){
                    $total_sku_num += $t->box_num;
                    $boxLocationArr[$t->location_ids] = $t->box_num;
                }
            }

            $now_total_num = $total_sku_num + $value;
            if ($locationSumNum < $now_total_num) {
                return  $custom_sku . '在仓库:' . $warehouse  . '平台：'.$platform_name. '的可用库存不足,请检查是否组合sku的子sku发货量超出可用库存';
            }

            if($value>0){
                if(isset($boxLocationArr[$key])){
                    DB::table('goods_transfers_box_detail')->where('box_id',$box_id)->where('custom_sku_id',$custom_sku_id)->where('location_ids',$key)->update(['box_num'=>$value+$boxLocationArr[$key]]);
                }else{
                    DB::table('goods_transfers_box_detail')->insert([
                        'box_id' => $box_id,
                        'custom_sku' => $custom_sku,
                        'custom_sku_id' => $custom_sku_id,
                        'box_num' => $value,
                        'location_ids' => $key
                    ]);
                }
            }elseif($value<0){
                return  $custom_sku . '的库存分配出错:' . $warehouse  . '分配数量:'.$value.'请联系技术人员处理';
            }
        }

        $box = DB::table('goods_transfers_box')->where('id',$box_id)->select('box_num')->first();
        if (!empty($box)) {
            $updateNum = $box->box_num + $num;
        } else {
            $updateNum = $num;
        }
        DB::table('goods_transfers_box')->where('id',$box_id)->update(['box_num'=>$updateNum]);

        $log['custom_sku_id'] = $custom_sku_id;
        $log['warehouse'] = $warehouse;
        $log['num'] = $num;
        $log['box_id'] = $box_id;
        $log['custom_sku'] = $custom_sku;
        $log['platform_id'] = $platform_id;
        $log['create_time'] = date('Y-m-d H:i:s', time());
        db::table('lock_inventory_log')->insert($log);
        return 1;
    }

    public function AddSysLog($params,$result,$name='',$function=''){
		$token = $params['token']??'';
        $addsyslog['user_id'] = $this->GetUserIdByToken($token);
        $addsyslog['create_time'] = date('Y-m-d H:i:s',time());
        $addsyslog['input'] =  $this->cut_str(json_encode($params),10000);
        $addsyslog['function'] = $function;
        $addsyslog['output'] = $this->cut_str(json_encode($result),10000);
        $addsyslog['name'] = $name;
        // $insert['user_id'] = $params['user_id'];
        // $insert['function'] = $params['function'];
        // $insert['name'] = $params['name'];
        // $insert['input'] = $params['input'];
        // $insert['output'] = $params['output'];
        // $insert['create_time'] = $params['create_time'];
        db::table('sys_log')->insert($addsyslog);
	}

    public function cut_str($str,$len,$suffix="..."){
		if(strlen($str) > $len){
			if(function_exists('mb_substr')){
					$str = mb_substr($str,0,$len,'utf-8').$suffix;
			}else{
					$str= substr($str,0,$len,'utf-8').$suffix;
			}     
		} 
		return $str; 
	}

    public function GetUserIdByToken($token){
		$users = db::table('users')->where('token',$token)->first();
		$user_id = 0;
		 if($users){
		   $user_id = $users->Id;
		 }
		 return $user_id;
	  }

    //根据清单号新增下架任务中转箱
    public function Addbox($order_no,$warehouse_id){
        $rnum = 0;
        $rnum = Redis::get('addbox');
        if($rnum==1){
            return false;
        }else{
            Redis::setex('addbox',12,1);
        }
        // $thisbox = DB::table('goods_transfers_box')->select('id')->orderBy('id','desc')->first();
        $insert = DB::table('goods_transfers_box')->insertGetId(['order_no'=>$order_no,'warehouse_id'=>$warehouse_id,'type'=>2]);
        $box_code =  'box'.$insert;
        DB::table('goods_transfers_box')->where('id',$insert)->update(['box_code'=>$box_code]);
        // if(empty($thisbox)){
        //     $insert = DB::table('goods_transfers_box')->insertGetId(['order_no'=>$order_no,'warehouse_id'=>$warehouse_id,'type'=>2]);
        //     $box_code =  'box'.$insert;
        //     DB::table('goods_transfers_box')->where('id',$insert)->update(['box_code'=>$box_code]);
        // }else{
        //     $insert = DB::table('goods_transfers_box')->insertGetId(['order_no'=>$order_no,'warehouse_id'=>$warehouse_id,'type'=>2]);
        //     $box_code =  'box'.$insert;
        //     DB::table('goods_transfers_box')->where('id',$insert)->update(['box_code'=>$box_code]);
        //     // $id = $thisbox->id + 1;
        //     // $box_code = 'box'.$id;
        //     // $insert = DB::table('goods_transfers_box')->insertGetId(['box_code'=>$box_code,'order_no'=>$order_no,'warehouse_id'=>$warehouse_id,'type'=>2]);
        // }
        if($insert){
            Redis::del('addbox');
            return $insert;
        }else{
            Redis::del('addbox');
            return false;
        }
    }


    // //根据清单号新增下架任务中转箱
    // public function Addboxb($order_no,$warehouse_id){

    //     $n_id = Redis::get('addbox_id');
    //     if(!$n_id){
    //         $n_id = DB::table('goods_transfers_box')->select('id')->orderBy('id','desc')->first()->id;
    //     }

    //     $n_id++;

    //     $box_id = DB::table('goods_transfers_box')->insertGetId(['','order_no'=>$order_no,'warehouse_id'=>$warehouse_id,'type'=>2]);
    // }

    //根据清单号新增上架任务中转箱
    public function Addbox2($order_no,$warehouse_id){
        $rnum = 0;
        $rnum = Redis::get('addbox');
        if($rnum==1){
            return false;
        }else{
            Redis::setex('addbox',6,1);
        }
        $thisbox = DB::table('goods_transfers_box')->select('id')->orderBy('id','desc')->first();

        if(empty($thisbox)){
            $insert = DB::table('goods_transfers_box')->insertGetId(['order_no'=>$order_no,'type'=>1,'warehouse_id'=>$warehouse_id]);
            $box_code =  'bc'.$insert;
            DB::table('goods_transfers_box')->where('id',$insert)->update(['box_code'=>$box_code]);
        }else{
            $id = $thisbox->id + 1;
            $box_code = 'bc'.$id;
            $insert = DB::table('goods_transfers_box')->insertGetId(['box_code'=>$box_code,'order_no'=>$order_no,'type'=>1,'warehouse_id'=>$warehouse_id]);
        }
        if($insert){
            Redis::del('addbox');
            return $insert;
        }else{
            Redis::del('addbox');
            return false;
        }
    }

    //新增库位变动日志
    public function add_location_log($location_id,$num,$custom_sku,$custom_sku_id,$spu,$spu_id,$type,$now_num,$order_no,$user_id,$time,$platform_id=0){
        $add = DB::table('cloudhouse_location_log')->insert([
            'location_id'=>$location_id,'num'=>$num,'custom_sku'=>$custom_sku,'custom_sku_id'=>$custom_sku_id,'spu'=>$spu,'spu_id'=>$spu_id,'type'=>$type,'now_num'=>$now_num,'order_no'=>$order_no,'user_id'=>$user_id,'time'=>$time,'platform_id'=>$platform_id
        ]);
        if(!$add){
            return false;
        }else{
            return true;
        }
    }


    //查看库位占用详情
    public function GetCustomSkuIventoryByLocationCodeInfo($custom_sku_id){
        $all = db::table('custom_sku_count as a')
            ->leftjoin('cloudhouse_warehouse_location as b','a.location_code','=','b.location_code')
            ->where('custom_sku_id',$custom_sku_id)
            ->select('a.count','a.no','b.id as location_id','b.location_code','b.warehouse_id')
            ->get();

        $return = [];
        foreach ($all as $v) {
            $use = DB::table('goods_transfers_box_detail as a')
                ->leftJoin('goods_transfers_box as b','a.box_id','=','b.id')
                ->leftjoin('goods_transfers as c','b.order_no','=','c.order_no')
                ->where('a.custom_sku_id',$custom_sku_id)
                ->where('a.location_ids',$v->location_id)
                ->whereIn('c.type_detail',$this->GetfieldTypeDetail())
                ->whereIn('c.is_push',[1,2,4])
                ->select('a.custom_sku_id','a.shelf_num','a.box_num','a.location_ids','c.out_house','c.type_detail','c.order_no')
                ->get();
            $v->box_num = 0;
            $v->detail = [];
            if($use){
                // $v->box_num = $use->box_num;
                // $v->shelf_num = $use->shelf_num;
                // $v->out_house = $use->out_house;
                // $v->type_detail = $use->type_detail;
                // $v->order_no = $use->order_no;
                foreach ($use as $uv) {
                    # code...
                    $v->box_num += $uv->box_num;
                }
                $v->detail = $use;
            }

            if($v->warehouse_id==1){
                $return['tongan'][] = $v;
            }
            if($v->warehouse_id==2){
                $return['quanzhou'][] = $v;
            }
            # code...
        }

        return $return;
    }
     /**
     * title string 标题
     * title_list array  列标
     * data array 数据
     */

     //excel导出 
     public function excel_expord($params){

        $tltle = $params['title'];
        $title_list = $params['title_list'];
        $protdata = json_decode(json_encode($params['data']), true);

        $obj = new \PHPExcel();

        $fileName = $tltle. date('Y-m-d');
        $fileType = 'xlsx';

        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle($tltle); //设置标题

        // 设置当前sheet
        $obj->setActiveSheetIndex(0);

        // 设置当前sheet的名称
        $obj->getActiveSheet()->setTitle($tltle);

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ", "CA", "CB", "CC", "CD", "CE", "CF", "CG", "CH", "CI", "CJ", "CK", "CL", "CM", "CN", "CO", "CP", "CQ", "CR", "CS", "CT", "CU", "CV", "CW", "CX", "CY", "CZ", "DA", "DB", "DC", "DD", "DE", "DF", "DG", "DH", "DI", "DJ");
        // 设置excel标题


        $index = 0;
        $data  = [];



        //过滤数据
        foreach ($protdata  as $pk => $onedata) {
            //过滤数据
            $one_new_data = [];
            foreach ($title_list as $k =>$v) {
                foreach ($onedata as $key => $value) {
                    # code...
                    
                    if($k!=''&&$k==$key){
                        $one_new_data[$k] = $value;
                    }
                }
            }
            $data[$pk]= $one_new_data;
                # code...
        }

    

        // 填充第一行数据
        foreach ($title_list as $k =>$v) {
        $obj->getActiveSheet()->setCellValue($cellName[$index] . '1', $v);
        $index++;
        }



        $i=0;
        // 填充第n(n>=2, n∈N*)行数据
        foreach ($data as $v) {
            # code...
            // echo $v[$key[$i]];
            $si = 0;
            foreach ($v as $sk => $sv) {
                # code...
                $obj->getActiveSheet()->setCellValue($cellName[$si] . ($i + 2), $sv, \PHPExcel_Cell_DataType::TYPE_STRING);
                if($sk=='img'){
                    if(!empty($sv)){
                        // echo '图片';
                        $name = str_replace('http://q.zity.cn/','/var/www/online/zity/public/admin/excel_img/',$sv);
                        // echo $name;
                        if($name){
                            $a = $this->httpcopy($sv,$name);
                            if($a['err']){
                                $imgtype = 'jpg';
                                if(strpos($sv, 'png')){
                                    $imgtype = 'png';
                                }
                                $name = '/var/www/online/zity/public/admin/excel_img/'.rand(1,100).time().'.'.$imgtype;
                                $ab = $this->httpcopy($sv,$name);
                                if($ab['err']){
                                    $name = '';
                                }
                            }
                            if(is_file($name)){
                                // $sv = './admin/img/d1662363206_cangsou.jpg';
                                try {
                                    //code...
                                    $sv = $name;
                                    $objDrawing  = new \PHPExcel_Worksheet_Drawing();
                                    // 获取图片地址
                                    $objDrawing->setPath($sv);
                                    // 设置图片存放在表格的位置
                                    $objDrawing->setCoordinates($cellName[$si] .($i + 2));
                                    // 设置表格宽度
                                    $obj->getActiveSheet()->getColumnDimension($cellName[$si])->setWidth(20);
                                    // 设置表格高度
                                    $obj->getActiveSheet()->getRowDimension(($i + 2))->setRowHeight(60);
                                    // 设置图片宽
                                    //$objDrawing->setWidth(80);
                                    // 设置图片高
                                    $objDrawing->setHeight(60);
                                    // 设置X方向偏移量
                                    $objDrawing->setOffsetX(10);
                                    // 设置Y方向偏移量
                                    $objDrawing->setOffsetY(10);
                                    $objDrawing->setWorksheet($obj->getActiveSheet());
                                } catch (\Throwable $th) {
                                    //throw $th;
                                    // echo $th->getMessage();
                                    $update['status'] = 2;
                                    $update['path'] = '';
                                    $update['msg'] =  $th->getMessage();
                                    exit;
                                }
                            }else{
                                $sv = $name;
                            }
                        }
                    }
                }
                   $si++;
            }
            $i++;
        }
        

        

        $length = count($title_list);
        $length2 = count($data);
        // 设置加粗和左对齐
        for ($i=0; $i < $length; $i++) { 
            # code...
            $obj->getActiveSheet()->getStyle($cellName[$i] . '1')->getFont()->setBold(true);
            // 设置第1-n行，左对齐
            for ($si = 1; $si <= $length2+1; $si++) {
                $obj->getActiveSheet()->getStyle($cellName[$i] . $si)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            }
        }

        // 导出
        // ob_clean();
        if ($fileType == 'xls') {
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xls');
            header('Cache-Control: max-age=1');
            $objWriter = new \PHPExcel_Writer_Excel5($obj);
            $objWriter->save('php://output');
            exit;
        } elseif ($fileType == 'xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx');
            header('Cache-Control: max-age=1');
            $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
            $objWriter->save('php://output');
            exit;
        }
    }

    function httpcopy($url, $file="/test.jpg",$timeout=60) {
        $file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;
        $dir = pathinfo($file,PATHINFO_DIRNAME);
        !is_dir($dir) && @mkdir($dir,0755,true);
        $url = str_replace(" ","%20",$url);

        if(function_exists('curl_init')) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            $temp = curl_exec($ch);
            try {
                file_put_contents($file, $temp) ;
            } catch (\Throwable $th) {
                // var_dump($th);
                return ['err'=>true,'data'=>$th->getMessage()];
            }

            if(@file_put_contents($file, $temp) && !curl_error($ch)) {
                //     $tofile = "/www/data/online/new_zity_php/public/admin/excel_img/".$newname;

                //     rename($file,$tofile);


                //    $url = "/admin/excel_img/".$newname;
                return ['err'=>false,'data'=>$file];
            } else {
                return ['err'=>true,'data'=>'下载远程图片失败'];
            }
        }
    }

    //获取fba库存
    public function getFbaInventory($params,$type){
      $product_detail = DB::table('product_detail');
        // $new_spu = array();
        // $old_spu = array();
        $returns = [];
        $ids = [];
         if($type=='spu'){
             if(is_array($params)){
                foreach ($params as $key=>$spu){
                    $spu_id = $this->GetSpuId($spu);
                    $ids[] =  $spu_id;
                    $returns[$spu_id] = $spu;
                    // $res = $this->GetNewSpu($spu);
                    // if($res){
                    //     $new_spu[$key] = $res;
                    // }else{
                    //     $new_spu[$key] = $spu;
                    // }
                    // $old_spu[$new_spu[$key]] = $spu;
                }
                 $product_detail = $product_detail->whereIn('spu_id',$spu_id);
             }else{
                 return false;
             }
         }
        if($type=='sku'){
            if(is_array($params)){
                foreach ($params as $key=>$spu){
                    $sku_id = $this->GetSkuId($spu);

                    $ids[] =  $sku_id;
                    $returns[$sku_id] = $spu;

                    // $res = $this->GetOldSku($spu);
                    // if($res){
                    //     $new_spu[$key] = $res;
                    // }else{
                    //     $new_spu[$key] = $spu;
                    // }
                    // $old_spu[$new_spu[$key]] = $spu;

                }

                $product_detail = $product_detail->whereIn('sku_id',$ids);
            }else{
                return false;
            }
        }
//        var_dump($ids);
        $product_detail= $product_detail->select('in_stock_num','in_bound_num','transfer_num','sellersku','spu','spu_id','sku_id')->get();
//        var_dump($product_detail);

  

        if($type=='spu'){
            foreach ($product_detail as $v){
                $v->spu = $returns[$v->spu_id];
                // $old_spu = $this->GetOldSpu($v->spu);
                // if($old_spu){
                //     $v->spu = $old_spu;
                // }
                // if(isset($old_spu[$v['spu']])){
                //     $product_detail[$k]['spu'] = $old_spu[$v['spu']];
                // }
            }
        }
        if($type=='sku'){
            foreach ($product_detail as $v){
                $v->sellersku = $returns[$v->sku_id];
                // $old_sku = $this->GetOldSku($v->sellersku);
                // if($old_sku){
                //     $v->sellersku = $old_sku;
                // }
                // if(isset($old_spu[$v['sellersku']])){
                //     $product_detail[$k]['sku'] = $old_spu[$v['sellersku']];
                // }
            }
        }

        $product_detail = json_decode(json_encode($product_detail),true);
        return $product_detail;
    }

    ///获取同安仓，泉州仓库存-新
    public function getHereInventory($params,$type){
        $result = [];
        if($type=='spu'){
            foreach ($params as $v) {
                $spu_id = $this->GetSpuId($v);
                $list = db::table('self_custom_sku')->where('spu_id',$spu_id)->select(DB::raw('sum(quanzhou_inventory) as quanzhou'),DB::raw('sum(tongan_inventory) as tongan'))->get();
                $result['quanzhou'][$v] = $list->quanzhou;
                $result['tongan'][$v] = $list->tongan;
            }
        }
        if($type=='custom_sku'){
            foreach ($params as $v) {
                $cus = db::table('self_custom_sku')->where('custom_sku',$v)->orwhere('old_custom_sku',$v)->first();
                $result['quanzhou'][$v] = $cus->quanzhou_inventory;
                $result['tongan'][$v] = $cus->tongan_inventory;
            }
        }

        return $result;

    }

    //获取同安仓，泉州仓库存
    public function getHereInventory_old($params,$type){
        $saihe_inventory = DB::table('saihe_inventory');
        // $new_spu = array();
        // $spulist = array();
        // $skulist = array();
        // $old_sku = array();
        $returns = [];
        $ids = [];
        if($type=='spu'){
            if(is_array($params)){
                foreach ($params as $key=>$spu){
                    // $res = $this->GetNewSpu($spu);
                    // if($res){
                    //     $new_spu[$key] = $res;
                    // }else{
                    //     $new_spu[$key] = $spu;
                    // }
                    // $spulist[$new_spu[$key]] = $spu;
                    $spu_id = $this->GetSpuId($spu);
                    $ids[] =  $spu_id;
                    $returns[$spu_id] = $spu;
                }
                $saihe_inventory = $saihe_inventory->whereIn('spu_id',$ids);
            } else{
                    return false;
            }
        }
        if($type=='custom_sku'){
            if(is_array($params)){
                foreach ($params as $key=>$sku){
                    $sku_id = $this->GetCustomSkuId($sku);
                    $ids[] =  $sku_id;
                    $returns[$sku_id] = $sku;
                    // $res = $this->GetCustomSkus($sku);
                    // if($res['old_custom_sku']!=''){
                    //     $old_sku[$key] = $res['old_custom_sku'];
                    //     $skulist[$res['old_custom_sku']] = $sku;
                    // }else{
                    //     $old_sku[$key] = $sku;
                    //     $skulist[$sku] = $sku;
                    // }
                }
                $saihe_inventory = $saihe_inventory->whereIn('custom_sku_id',$ids);
            }else{
               return false;
            }
        }

        $saihe_inventory = $saihe_inventory->whereIn('warehouse_id',[2,386,560])->select('good_num','warehouse_id','client_sku','spu','spu_id','custom_sku_id')->get();
        $result = array();
        if($type=='spu'){
            foreach ($saihe_inventory as $v){
                // if(isset($spulist[$v->spu])){
                //     $v->spu = $spulist[$v->spu];
                // }
                $v->spu = $returns[$v->spu_id];
                $result['tongan'][$v->spu] = 0;
                $result['quanzhou'][$v->spu] = 0;
                if($v->warehouse_id==2||$v->warehouse_id==386){
                    if(isset($result['tongan'][$v->spu])){
                        $result['tongan'][$v->spu] += $v->good_num;
                    }else{
                        $result['tongan'][$v->spu] = $v->good_num;
                    }
                }
                if($v->warehouse_id==560){
                    if(isset($result['quanzhou'][$v->spu])){
                        $result['quanzhou'][$v->spu] += $v->good_num;
                    }else{
                        $result['quanzhou'][$v->spu] = $v->good_num;
                    }
                }
            }


        }

        if($type=='custom_sku'){
            foreach ($saihe_inventory as $v){


                // if(isset($skulist[$v->client_sku])){
                //     $v->client_sku = $skulist[$v->client_sku];
                // }
                $v->client_sku = $returns[$v->custom_sku_id];
                // $strtoupper_sku = strtoupper($v->client_sku);
                // if(isset($skulist[$strtoupper_sku])){
                //     $v->client_sku = $skulist[$strtoupper_sku];
                // }
                $result['tongan'][$v->client_sku] = 0;
                $result['quanzhou'][$v->client_sku] = 0;
                if($v->warehouse_id==2||$v->warehouse_id==386){
                    if(isset($result['tongan'][$v->client_sku])){
                        $result['tongan'][$v->client_sku] += $v->good_num;
                    }else{
                        $result['tongan'][$v->client_sku] = $v->good_num;
                    }
                }
                if($v->warehouse_id==560){
                    if(isset($result['quanzhou'][$v->client_sku])){
                        $result['quanzhou'][$v->client_sku] += $v->good_num;
                    }else{
                        $result['quanzhou'][$v->client_sku] = $v->good_num;
                    }
                }
            }

        }
        return $result;

    }

    //店铺月销量缓存
    public function getMonthSales($sku,$shop,$month,$year){

        $start_time = date($year.'-'.$month.'-01 00:00:00');
        $start_int = strtotime($start_time);
        $end_int = strtotime("+5 months",$start_int);
        $end_time = date('Y-m-d H:i:s',$end_int);
        $name = 'last5_sales:'.$year.$month.$shop;
        $num = Redis::Hget($name,$sku);
        if(!$num){
//            DB::connection()->enableQueryLog();
            $sku_id = $this->GetSkuId($sku);
            $res = Db::table('amazon_order_item')->where('sku_id',$sku_id)->where('shop_id',$shop)->where('order_status','!=','Canceled')->whereBetween('amazon_time', [$start_time, $end_time])->select('quantity_ordered')->get();
//            print_r(DB::getQueryLog());


            if(!empty($res)){
                $res = json_decode(json_encode($res),true);
                $order = array_column($res,'quantity_ordered');
                $num = array_sum($order);
            }else{
                $num = 0;
            }
            Redis::Hset($name,$sku,$num);
        }

        return $num;
    }
    
    public function is_leapyear($day){
        if ($day%4==0&&($day%100!=0 || $day%400==0)){
            return true;
        }else{
            return false;
        }
    }

    //    /**
//     * @Desc: 通过spu查询详情
//     * @param $spu
//     * @return false|mixed
//     * @author: Liu Sinian
//     * @Time: 2023/3/10 16:20
//     */
//    public function spuGetSpuModel($spu)
//    {
//        $spuMdl = Redis::Hget('datacache:spuGetSpuModel',$spu);
//        if(!$spuMdl){
//            $spuMdl = Db::table('self_spu')->where('spu',$spu)->orwhere('old_spu',$spu)->first();
//            if($spuMdl){
//                Redis::Hset('datacache:spuGetSpuModel',$spu,json_encode($spuMdl));
//            }else{
//                $spuMdl = false;
//            }
//        }else{
//            $spuMdl = json_decode($spuMdl,true);
//        }
//        return $spuMdl;
//    }
//
//    /**
//     * @Desc:通过id查询base_sku详情
//     * @param $baseSpuId
//     * @return false|mixed
//     * @author: Liu Sinian
//     * @Time: 2023/3/10 16:20
//     */
//    public function idGetBaseSpuModel($id)
//    {
//        $baseSpuMdl = Redis::Hget('datacache:idGetBaseSpuModel',$id);
//        if(!$baseSpuMdl){
//            $baseSpuMdl = Db::table('self_base_spu')->where('id',$id)->first();
//            if($baseSpuMdl){
//                Redis::Hset('datacache:idGetBaseSpuModel',$id,json_encode($baseSpuMdl));
//            }else{
//                $baseSpuMdl = false;
//            }
//        }else{
//            $baseSpuMdl = json_decode($baseSpuMdl,true);
//        }
//        return $baseSpuMdl;
//    }
    /**
     * @Desc:过滤非表字段数据
     * @param $filterFiled 过滤的数据
     * @param $tableName 数据表名称
     * @return mixed
     * @author: Liu Sinian
     * @Time: 2023/3/22 10:49
     */
    function allowField($filterFiled, $tableName){
        $fields = Schema::getColumnListing($tableName);
        if($fields){
            $pFileds = array_keys($filterFiled);
            $diffs= array_diff($pFileds, $fields);
            if(!empty($diffs)){
                foreach($diffs as  $v){
                    unset($filterFiled[$v]);
                }
            }
        }
        return $filterFiled;
    }

    /**
     * @Desc:时间戳转换
     * @param $timestamp
     * @return string
     * @author: Liu Sinian
     * @Time: 2023/4/24 16:48
     */
    public function timestampConversion($timestamp = 0)
    {
        $day = floor($timestamp/(3600*24));
        $second = $timestamp%(3600*24);//除去整天之后剩余的时间
        $hour = floor($second/3600);
        $second = $second%3600;//除去整小时之后剩余的时间
        $minute = floor($second/60);
        $second = $second%60;//除去整分钟之后剩余的时间
//        if($day >0 && $hour >0){
//            return $day.'天'.$hour.'小时' ;
//        }
//        if($day == 0 && $hour >0){
//            return $hour.'小时'.$minute.'分钟';
//        }
//        if($day ==0 && $hour ==0 && $minute >0){
//            return $minute.'分钟' ;
//        }

//        return $day.'天'.$hour.'小时'.$minute.'分'.$second.'秒';

        return $day.'天'.$hour.'小时'.$minute.'分钟';
    }



    /**
     * @Desc:查询锁定库存
     * @param $custom_sku_id
     * @return int or array
     * @author: 严威
     * @Time: 2023/5/8 17:44
     */
    public function lock_inventory($custom_sku_id,$platform_id=array()){
        $list = DB::table('goods_transfers_box_detail as a')
            ->leftjoin('goods_transfers_box as b','a.box_id','=','b.id')
            ->leftjoin('goods_transfers as c','b.order_no','=','c.order_no');

        if(is_array($custom_sku_id)){
            $list = $list->whereIn('a.custom_sku_id',$custom_sku_id)->whereIn('c.is_push',[1,2,4])
                ->whereIn('c.type_detail',$this->GetfieldTypeDetail3());
        }else{
            $list = $list->where('a.custom_sku_id',$custom_sku_id)->whereIn('c.is_push',[1,2,4])
                ->whereIn('c.type_detail',$this->GetfieldTypeDetail3());
        }
        if(!empty($platform_id)){
            $list = $list->whereIn('c.platform_id',$platform_id);
        }

        $list = $list->where('c.anomaly_order','!=','次品出库')
            ->select('a.box_num','a.shelf_num','a.custom_sku_id','c.platform_id','b.type','c.out_house','c.in_house')->get();

        $res = array();
        if($list->isEmpty()){
            return $res;
        }else{
            foreach ($list as $ll){
                if($ll->type==2){
                    if(isset($res[$ll->custom_sku_id][$ll->out_house])){
                        $res[$ll->custom_sku_id][$ll->out_house] += $ll->box_num - $ll->shelf_num;
                    }else{
                        $res[$ll->custom_sku_id][$ll->out_house] = $ll->box_num - $ll->shelf_num;
                    }
                }
            }
            return $res;
        }
    }


    /**
     * @Desc:查询整个仓库锁定库存
     * @param $custom_sku_id
     * @return int or array
     * @author: 严威
     * @Time: 2023/5/8 17:44
     */
    public function lock_inventoryc($custom_sku_id){
        $list = DB::table('goods_transfers_box_detail as a')->leftJoin('goods_transfers_box as b','a.box_id','=','b.id')->leftjoin('goods_transfers as c','b.order_no','=','c.order_no');
        if(is_array($custom_sku_id)){
            $list = $list->whereIn('a.custom_sku_id',$custom_sku_id);
        }else{
            $list = $list->where('a.custom_sku_id',$custom_sku_id);
        }
        $list = $list->whereIn('c.type_detail',$this->GetfieldTypeDetail())->whereIn('c.is_push',[1,2,4])->select('a.custom_sku_id','a.shelf_num','a.box_num','a.location_ids','c.out_house')->get();

        $res = array();
        if($list->isEmpty()){
            return $res;
        }else{
            foreach ($list as $ll){
                if(isset($res[$ll->custom_sku_id][$ll->out_house])){
                    $res[$ll->custom_sku_id][$ll->out_house] += $ll->box_num;
                }else{
                    $res[$ll->custom_sku_id][$ll->out_house] = $ll->box_num;
                }
            }
            return $res;
        }
    }


    //查询某个库位上某个平台sku的锁定库存-实时
    public function lock_inventory_d($custom_sku_id,$platform_id=0,$location_id=0,$warehouse_id=0){
        $list = DB::table('goods_transfers_box_detail as a')
            ->leftjoin('goods_transfers_box as b','a.box_id','=','b.id')
            ->leftjoin('goods_transfers as c','b.order_no','=','c.order_no');

        if(is_array($custom_sku_id)){
            $list = $list->whereIn('a.custom_sku_id',$custom_sku_id)->whereIn('c.is_push',[1,2,4])
                ->whereIn('c.type_detail',$this->GetfieldTypeDetail3());
        }else{
            $list = $list->where('a.custom_sku_id',$custom_sku_id)->whereIn('c.is_push',[1,2,4])
                ->whereIn('c.type_detail',$this->GetfieldTypeDetail3());
        }
        if($platform_id!=0){
            $list = $list->where('c.platform_id',$platform_id);
        }
        if($location_id!=0){
            $list = $list->where('a.location_ids',$location_id);
        }
        if($warehouse_id!=0){
            $list = $list->where('c.out_house',$warehouse_id);
        }
        $list = $list->select('a.box_num','a.shelf_num','a.location_ids','a.custom_sku_id','c.platform_id','b.type')->get();
        $res = [];

        if($list->isEmpty()){
            return $res;
        }else{
            foreach ($list as $ll){
                if($ll->type==1){
                    $balance = $ll->shelf_num;
                }
                if($ll->type==2){
                    $balance = $ll->box_num - $ll->shelf_num;
                }
                if(isset($res[$ll->custom_sku_id][$ll->location_ids][$ll->platform_id])){
                    $res[$ll->custom_sku_id][$ll->location_ids][$ll->platform_id] += $balance;
                }else{
                    $res[$ll->custom_sku_id][$ll->location_ids][$ll->platform_id] = $balance;
                }
            }
            return $res;
        }
    }


        //查询某个库位上某个平台sku的锁定库存-实时
        public function lock_inventory_dd($custom_sku_id,$platform_id=0){
            $list = DB::table('goods_transfers_box_detail as a')
                ->leftjoin('goods_transfers_box as b','a.box_id','=','b.id')
                ->leftjoin('goods_transfers as c','b.order_no','=','c.order_no');
    
            if(is_array($custom_sku_id)){
                $list = $list->whereIn('a.custom_sku_id',$custom_sku_id)->whereIn('c.is_push',[1,2,4])
                    ->whereIn('c.type_detail',$this->GetfieldTypeDetail());
            }else{
                $list = $list->where('a.custom_sku_id',$custom_sku_id)->whereIn('c.is_push',[1,2,4])
                    ->whereIn('c.type_detail',$this->GetfieldTypeDetail());
            }
            if($platform_id!=0){
                $list = $list->where('c.platform_id',$platform_id);
            }
            $list = $list->select('a.box_num','a.shelf_num','a.location_ids','a.custom_sku_id')->get();
            $res = [];
    
            if($list->isEmpty()){
                return $res;
            }else{
                foreach ($list as $ll){
                    $balance = $ll->box_num - $ll->shelf_num;
                    if(isset($res[$ll->custom_sku_id][$ll->location_ids])){
                        $res[$ll->custom_sku_id][$ll->location_ids] += $balance;
                    }else{
                        $res[$ll->custom_sku_id][$ll->location_ids] = $balance;
                    }
                    // $res[$ll->custom_sku_id][$ll->warehouse_id] = $ll->lock_num;
                }
                return $res;
            }
        }

    //根据库存sku和仓库查询库存明细 --严威
    public function inventoryDetail($custom_sku_id,$warehouse_id,$skuData=array()){
        if(empty($skuData)){
            $self_custom_sku = DB::table('self_custom_sku')
                ->whereIn('id',$custom_sku_id)
                ->select('tongan_inventory','id')
                ->get()
                ->toArray();
            $self_custom_sku = json_decode(json_encode($self_custom_sku),true);
        }else{
            $self_custom_sku = json_decode(json_encode($skuData),true);
        }

        $data = array();

        foreach ($self_custom_sku as $s){
                $data[$s['id']]['inventory'] = $s[self::WAREHOUSE[$warehouse_id]];//当前仓库库存
                $data[$s['id']]['shelf_num'] = 0;//已推单未操作库存
                $data[$s['id']]['delist_num'] = 0;//已拣货库存
                $data[$s['id']]['lock_num'] = 0;//锁定库存
                $data[$s['id']]['occupy_num'] = 0;//已占用库存
                $data[$s['id']]['bad_num'] = 0;//次品库存
        }
        $list = DB::table('goods_transfers_box_detail as a')
            ->leftjoin('goods_transfers_box as b','a.box_id','=','b.id')
            ->leftjoin('goods_transfers as c','b.order_no','=','c.order_no')
            ->where('b.warehouse_id',$warehouse_id)
            ->whereIn('a.custom_sku_id',$custom_sku_id)
            ->whereIn('c.is_push',[1,2,4])
            ->whereIn('c.type_detail',$this->GetFieldTypeDetail())
            ->select('a.box_num','a.shelf_num','a.location_ids','a.custom_sku_id','c.platform_id','b.type','c.order_no','type_detail')
            ->get()
            ->toArray();
//        var_dump($list);
        $request = DB::table('goods_transfers as a')->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
            ->where(function($query) use($warehouse_id){
                $query->where('a.out_house',$warehouse_id)->orWhere('a.in_house',$warehouse_id);
            })
            ->whereIn('b.custom_sku_id',$custom_sku_id)
            ->whereIn('a.is_push',[1,2,4])
            ->whereIn('a.type_detail',$this->GetFieldTypeDetail3())
            ->select('b.transfers_num', 'b.custom_sku_id','a.order_no', 'a.type_detail','b.receive_num','a.out_house','a.in_house')
            ->get()
            ->toArray();

        //次品库存查询
//        $badnum = DB::table('cloudhouse_location_num as a')
//            ->leftjoin('cloudhouse_warehouse_location as b','a.location_id','=','b.id')
//            ->where('b.type',2)
//            ->where('b.warehouse_id',$warehouse_id)
//            ->whereIn('a.custom_sku_id',$custom_sku_id)
//            ->select('a.num','a.custom_sku_id')->get()->toArray();

        $data['shelf_num'] = 0;//已推单未操作库存
        $data['delist_num'] = 0;//已拣货库存
        $data['lock_num'] = 0;//锁定中库存
        $data['occupy_num'] = 0;//已占用库存

        if(!empty($list)){
            foreach ($list as $v){
                if($v->type==2){
                    $data[$v->custom_sku_id]['lock_num'] += $v->box_num - $v->shelf_num;
                    $data[$v->custom_sku_id]['delist_num'] += $v->shelf_num;
                }
            }
        }

        if(!empty($request)){
            foreach ($request as $d){
                if(in_array($d->type_detail,$this->GetFieldTypeDetail2())){
                    if($warehouse_id == $d->in_house){
                        $data[$d->custom_sku_id]['shelf_num'] += $d->transfers_num - $d->receive_num;
                    }
                }
                if(in_array($d->type_detail,$this->GetFieldTypeDetail())){
                    if($warehouse_id == $d->out_house) {
                        $data[$d->custom_sku_id]['occupy_num'] += $d->transfers_num;
                    }
                }
            }
        }

//        if(!empty($badnum)){
//            foreach ($badnum as $bb){
//                $data[$bb->custom_sku_id]['bad_num'] += $bb->num;
//            }
//        }

        foreach ($custom_sku_id as $val){
            $data[$val]['intstock_num'] = $data[$val]['inventory'] - $data[$val]['occupy_num'] - $data[$val]['bad_num'] ;//可用库存
        }

        return $data;

    }


    //根据库存sku和仓库和平台查询库存明细 --严威
    public function inventoryPlatformDetail($custom_sku_id,$warehouse_id = 0,$platform_id=array(),$type=1){
        if(empty($platform_id)){
            $platform = DB::table('platform')->select('Id')->get()->toArray();
            $platform_id = array_column($platform,'Id');
        }

        $data = array();
        foreach ($platform_id as $p){
            $data[$p]['inventory'] = 0;
            $data[$p]['shelf_num'] = 0;
            $data[$p]['platform_shelf_num'] = 0;
            $data[$p]['lock_num'] = 0;
            $data[$p]['delist_num'] = 0;
            $data[$p]['occupy_num'] = 0;
        }

//        DB::connection()->enableQueryLog();
        $custom_sku = DB::table('cloudhouse_location_num as a')
            ->leftJoin('cloudhouse_warehouse_location as b','a.location_id','=','b.id')
            ->where('a.custom_sku_id',$custom_sku_id)
            ->where('b.warehouse_id',$warehouse_id)
            ->where('b.type',$type)
            ->whereIn('a.platform_id',$platform_id)
            ->select('a.num','a.location_id','a.platform_id')
            ->get()
            ->toArray();
//        if($warehouse_id==21){
//            var_dump(DB::getQueryLog());
//        }
        if(!empty($custom_sku)){
            foreach ($custom_sku as $v){
                if(isset($data[$v->platform_id]['inventory'])){
                    $data[$v->platform_id]['inventory'] += $v->num;
                }else{
                    $data[$v->platform_id]['inventory'] = $v->num;
                }
            }
        }
        $list = DB::table('goods_transfers_box_detail as a')
            ->leftjoin('goods_transfers_box as b','a.box_id','=','b.id')
            ->leftjoin('goods_transfers as c','b.order_no','=','c.order_no')
            ->where('a.custom_sku_id',$custom_sku_id)
            ->where('b.warehouse_id', $warehouse_id)
            ->whereIn('c.platform_id',$platform_id)
            ->whereIn('c.is_push',[1,2,4])
            ->whereIn('c.type_detail',$this->GetFieldTypeDetail());
        if($type==2){
            $list = $list->where('c.anomaly_order','次品出库');
        }else{
            $list = $list->where('c.anomaly_order','!=','次品出库');
        }
        $list = $list->select('a.box_num','a.shelf_num','a.location_ids','a.custom_sku_id','c.platform_id','b.type')
            ->get()
            ->toArray();
        if(!empty($list)){
            foreach ($list as $d){
                if($d->type==2){
                    $data[$d->platform_id]['lock_num'] += $d->box_num - $d->shelf_num;
                    $data[$d->platform_id]['delist_num'] += $d->shelf_num;
                }
            }
        }

        $request = DB::table('goods_transfers as a')
            ->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
            ->where(function($query) use($warehouse_id){
                $query->where('a.out_house',$warehouse_id)->orWhere('a.in_house',$warehouse_id);
            })
            ->where('b.custom_sku_id',$custom_sku_id)
            ->whereIn('a.platform_id',$platform_id)
            ->whereIn('a.is_push',[1,2,4])
            ->whereIn('a.type_detail',$this->GetFieldTypeDetail3());
        if($type==2){
            $request = $request->where('a.anomaly_order','次品出库');
        }
        $request = $request->select('b.transfers_num', 'b.custom_sku_id','a.order_no', 'a.type_detail','b.receive_num','a.out_house','a.in_house','a.platform_id')
            ->get()
            ->toArray();
       
        if(!empty($request)){
            foreach ($request as $r){
                if(in_array($r->type_detail,$this->GetFieldTypeDetail2())){
                    if($warehouse_id == $r->in_house){
                        $data[$r->platform_id]['shelf_num'] += $r->transfers_num - $r->receive_num;
                    }
                }
                if(in_array($r->type_detail,$this->GetFieldTypeDetail())){
                    if($warehouse_id == $r->out_house) {
                        $data[$r->platform_id]['occupy_num'] += $r->transfers_num;
                    }
                }
            }
        }


        foreach ($platform_id as $p){
            $data[$p]['intsock_num'] = $data[$p]['inventory']-$data[$p]['lock_num'];//当前仓库的平台可用库存
            $data[$p]['platform_name'] = $this->GetPlatform($p)['name'];
            $data[$p]['platform_id'] = $p;
        }
        $data = array_values($data);
        return $data;

    }

    /**
     * 根据库存sku和仓库，库位，平台，查询库存明细
     * @param $custom_sku_id
     * @param int $warehouse_id
     * @param int $location_id
     * @param int $platform_id
     * @return int[]
     * @author: WZY
     * @Time: 2023/8/11
     */
    public function inventoryDetailByWlp($custom_sku_id, $warehouse_id = 0, $location_id = 0, $platform_id = 0)
    {
        $query = DB::table('goods_transfers_box_detail as a')
            ->select('a.box_num', 'a.shelf_num', 'a.location_ids', 'a.custom_sku_id', 'c.platform_id', 'b.type')
            ->leftjoin('goods_transfers_box as b', 'a.box_id', '=', 'b.id')
            ->leftjoin('goods_transfers as c', 'b.order_no', '=', 'c.order_no')
            ->where('c.anomaly_order','!=','次品出库')
            ->where('a.custom_sku_id', $custom_sku_id)
            ->whereIn('c.is_push', [1, 2, 4])
            ->whereIn('c.type_detail', $this->GetFieldTypeDetail3());
        if ($warehouse_id) {
            $query->where('b.warehouse_id', $warehouse_id);
        }

        if ($location_id) {
            $query->where('a.location_ids', $location_id);
        }

        if ($platform_id) {
            $query->where('c.platform_id', $platform_id);
        }

        $list = $query->get();

        $data = [
            'shelf_num'  => 0,//已推单未入库库存
            'lock_num'   => 0,//锁定中库存
            'delist_num' => 0,//已拣货库存
        ];

        if ($list->isEmpty()) {
            return $data;
        }

        foreach ($list as $d) {
           if ($d->type == 2) {
                $data['lock_num']   += $d->box_num - $d->shelf_num;
                $data['delist_num'] += $d->shelf_num;
            }
        }

        return $data;
    }

    /**
     * 根据库存sku和仓库，库位，平台，批量查询库存明细
     * @param $custom_sku_ids
     * @param array $warehouse_ids
     * @param array $location_ids
     * @param array $platform_ids
     * @return array
     * @author: WZY
     * @Time: 2023/8/23
     */
    public function batchInventoryDetailByWlp($custom_sku_ids, $warehouse_ids = [], $location_ids = [], $platform_ids = [])
    {
        $query = DB::table('goods_transfers_box_detail as a')
            ->select([
                'a.box_num',
                'a.shelf_num',
                'a.location_ids',
                'a.custom_sku_id',
                'c.platform_id',
                'b.warehouse_id',
                'b.type'
            ])
            ->leftjoin('goods_transfers_box as b', 'a.box_id', '=', 'b.id')
            ->leftjoin('goods_transfers as c', 'b.order_no', '=', 'c.order_no')
            ->where('c.anomaly_order','!=','次品出库')
            ->whereIn('a.custom_sku_id', $custom_sku_ids)
            ->whereIn('c.is_push', [1, 2, 4])
            ->whereIn('c.type_detail', $this->GetFieldTypeDetail());

        if ($warehouse_ids) {
            $query->whereIn('b.warehouse_id', $warehouse_ids);
        }

        if ($location_ids) {
            $query->whereIn('a.location_ids', $location_ids);
        }

        if ($platform_ids) {
            $query->whereIn('c.platform_id', $platform_ids);
        }

        $list = $query->get();

        $data = [
//            'shelf_num'  => 0,//已上架未入库库存
//            'lock_num'   => 0,//锁定中库存
//            'delist_num' => 0,//已拣货库存
        ];

        if ($list->isEmpty()) {
            return $data;
        }

        foreach ($list as $d) {

            $key = $d->custom_sku_id;

            if ($warehouse_ids) {
                $key .= '_' . $d->warehouse_id;
            }

            if ($location_ids) {
                $key .= '_' . $d->location_ids;
            }

            if ($platform_ids) {
                $key .= '_' . $d->platform_id;
            }

            if (isset($data[$key])) {
                $data[$key]['lock_num']   += $d->box_num - $d->shelf_num;
                $data[$key]['delist_num'] += $d->shelf_num;
            } else {
                $data[$key]['shelf_num']  = 0;
                $data[$key]['lock_num']   = $d->box_num - $d->shelf_num;
                $data[$key]['delist_num'] = $d->shelf_num;

            }

        }

        return $data;
    }

    public function getInventoryDetailByWlp($custom_sku_ids, $warehouse_ids = [], $location_ids = [], $platform_ids = [])
    {
        $locationNumQuery = DB::table('cloudhouse_location_num as a')
            ->select([
                'a.id',
                'a.custom_sku_id',
                'a.location_id',
                'a.platform_id',
                'a.num',
                'b.warehouse_id',
            ])
            ->leftJoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
            ->where('b.type',1)
            ->whereIn('a.custom_sku_id', $custom_sku_ids);
        if ($warehouse_ids) {
            $locationNumQuery->whereIn('b.warehouse_id', $warehouse_ids);
        }

        if ($location_ids) {
            $locationNumQuery->whereIn('a.location_ids', $location_ids);
        }

        if ($platform_ids) {
            $locationNumQuery->whereIn('a.platform_id', $platform_ids);
        }

        $locationNumList = $locationNumQuery->get();


        $inventory = [];

        foreach ($locationNumList as $v) {
            $key = $v->custom_sku_id;

            if ($warehouse_ids) {
                $key .= '_' . $v->warehouse_id;
            }

            if ($location_ids) {
                $key .= '_' . $v->location_ids;
            }

            if ($platform_ids) {
                $key .= '_' . $v->platform_id;
            }

            if (isset($inventory[$key])) {
                $inventory[$key]['num']        += $v->num;
                $inventory[$key]['usable_num'] += $v->num;

            } else {
                $inventory[$key]['num']        = $v->num;
                $inventory[$key]['usable_num'] = $v->num;
                $inventory[$key]['lock_num']   = 0;
                $inventory[$key]['delist_num'] = 0;
                $inventory[$key]['shelf_num']  = 0;
            }
        }


        $query = DB::table('goods_transfers_box_detail as a')
            ->select([
                'a.box_num',
                'a.shelf_num',
                'a.location_ids',
                'a.custom_sku_id',
                'c.platform_id',
                'b.warehouse_id',
                'b.type'
            ])
            ->leftjoin('goods_transfers_box as b', 'a.box_id', '=', 'b.id')
            ->leftjoin('goods_transfers as c', 'b.order_no', '=', 'c.order_no')
            ->where('c.anomaly_order','!=','次品出库')
            ->whereIn('a.custom_sku_id', $custom_sku_ids)
            ->whereIn('c.is_push', [1, 2, 4])
            ->whereIn('c.type_detail', $this->GetFieldTypeDetail());

        if ($warehouse_ids) {
            $query->whereIn('b.warehouse_id', $warehouse_ids);
        }

        if ($location_ids) {
            $query->whereIn('a.location_ids', $location_ids);
        }

        if ($platform_ids) {
            $query->whereIn('c.platform_id', $platform_ids);
        }

        $list = $query->get();

        foreach ($list as $d) {

            $key = $d->custom_sku_id;

            if ($warehouse_ids) {
                $key .= '_' . $d->warehouse_id;
            }

            if ($location_ids) {
                $key .= '_' . $d->location_ids;
            }

            if ($platform_ids) {
                $key .= '_' . $d->platform_id;
            }

            if (isset($inventory[$key])) {
                $inventory[$key]['lock_num']   += $d->box_num - $d->shelf_num;
                $inventory[$key]['delist_num'] += $d->shelf_num;
            } else {
                $inventory[$key]['num'] = 0;
                $inventory[$key]['shelf_num']  = 0;
                $inventory[$key]['lock_num']   = $d->box_num - $d->shelf_num;
                $inventory[$key]['delist_num'] = $d->shelf_num;
            }
        }

        foreach ($inventory as $key => $value) {
            $usableNum                     = $value['num'] - $value['lock_num'];
            $inventory[$key]['usable_num'] = $usableNum >= 0 ? $usableNum : 0;
        }

        return $inventory;
    }




    /**
     * @Desc:获取库位库存sku锁定库存-实时
     * @param $locationId
     * @param $custom_sku_id
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/6/25 10:47
     */
    public function GetLocationCustomSkuLockNum($custom_sku_id, $locationId = 0, $warehouseId = 0, $platformId = 0){
        $list = DB::table('goods_transfers_box_detail as a')
            ->leftjoin('goods_transfers_box as b','a.box_id','=','b.id')
            ->leftjoin('goods_transfers as c','b.order_no','=','c.order_no')
            ->leftjoin('self_custom_sku as d', 'a.custom_sku_id', '=', 'd.id')
            ->leftjoin('cloudhouse_warehouse_location as e', 'e.id', '=', 'a.location_ids')
            ->leftjoin('cloudhouse_warehouse as f', 'f.id', '=', 'e.warehouse_id');
        if ($locationId){
            $list = $list->where('a.location_ids', $locationId);
        }
        if ($warehouseId){
            $list = $list->where('e.warehouse_id', $warehouseId);
        }
        if ($platformId){
            $list = $list->where('c.platform_id', $platformId);
        }

        if(is_array($custom_sku_id)){
            $list = $list->whereIn('a.custom_sku_id',$custom_sku_id)->whereIn('c.is_push',[1,2,4])
                ->whereIn('c.type_detail',$this->GetFieldTypeDetail())
            ;
        }else{
            $list = $list->where('a.custom_sku_id',$custom_sku_id)->whereIn('c.is_push',[1,2,4])
                ->whereIn('c.type_detail',$this->GetFieldTypeDetail())
            ;
        }

        $list = $list->select('a.box_num','a.shelf_num','a.location_ids','a.custom_sku_id', 'c.platform_id', 'b.order_no', 'a.box_id', 'd.id as custom_sku_id',
            'c.type_detail','d.spu_id', 'd.name', 'e.location_name', 'e.location_code','f.warehouse_name', 'c.user_id', 'c.createtime as create_time', 'e.platform_name')->get();
        $res = [];
        $platformMdl = db::table('platform')->get();
        $platformList = [];
        foreach ($platformMdl as $v){
            $platformList[$v->Id] = $v->name;
        }
        if($list->isEmpty()){
            return $res;
        }else{
            foreach ($list as $ll){
                $balance = $ll->box_num - $ll->shelf_num;
//                if(isset($res[$ll->custom_sku_id])){
//                    $res[$ll->custom_sku_id] += $balance;
//                }else{
//                    $res[$ll->custom_sku_id] = $balance;
//                }
                $ll->type_name = $this->type_detail_arr[$ll->type_detail];
                $ll->lock_num = $balance;
                $ll->user_name = $this->GetUsers($ll->user_id)['account'] ?? '';
                $ll->platform_name = $platformList[$ll->platform_id] ?? '';
            }
            $res = json_decode(json_encode($list), true);

            return $res;
        }
    }

    public function GetCustomSkuLock($customSkuId, $warehouseId = 0, $locationId = 0)
    {
        $list = DB::table('goods_transfers as a')
            ->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no');
        if(is_array($customSkuId)){
            $list = $list->whereIn('b.custom_sku_id',$customSkuId);
        }else{
            $list = $list->where('b.custom_sku_id',$customSkuId);
        }
        if (empty($warehouseId)){
            $list = $list->where('a.out_house', $warehouseId);
        }
        $list = $list->whereIn('a.is_push',[1,2,4])->select('b.custom_sku_id','b.transfers_num','a.out_house')->get();

        $res = array();
        if($list->isEmpty()){
            return $res;
        }else{
            foreach ($list as $ll){
                if(isset($res[$ll->custom_sku_id][$ll->out_house])){
                    $res[$ll->custom_sku_id][$ll->out_house] += $ll->transfers_num;
                }else{
                    $res[$ll->custom_sku_id][$ll->out_house] = $ll->transfers_num;
                }
            }
            return $res;
        }
    }

    //excel公共导入
    //$p['row'] = ['spu','color','size'];
    //$p['file'] = $file;
    //$this->CommonExcelImport($p);

    public function CommonExcelImport($params){
        ////获取Excel文件数据
        $file = $params['file'];
        //spu custom_sku sku color_id size_id  platform_id one_cate three_cate shop_id name
          //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }

        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);
        $add_list = array();
        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        $allColumn = $params['row'];

        $start =  $params['start']??2;

        for ($j = $start; $j <= $allRow; $j++) {
            // for ($ci=0; $ci <  $allColumn; $ci++) { 
            //     # code...
            //     $add_list[$j - 2][$ci] = trim($Sheet->getCellByColumnAndRow($ci, $j)->getValue())??'';
            // }
            $ci=0;
            foreach ($allColumn as $v) {
                # code...
                $value = trim($Sheet->getCellByColumnAndRow($ci, $j)->getValue())??'';
                if(strcspn($value,'=') == 0){
                    $value = $Sheet->getCellByColumnAndRow($ci, $j)->getOldCalculatedValue();//获取单元格使用了公式的值
                }
                $add_list[$j - $start][$v] =$value;
                $ci++;
            }

        }

        return $add_list;
    }



    /**
     * @Desc:用fasin查找fasin信息
     * @param $fasin
     * @return false|mixed
     * @author: Liu Sinian
     * @Time: 2023/5/22 17:05
     */
    public function GetFasinCode($fasin){
        $res = Redis::Hget('datacache:amazon_fasin',$fasin);
        if(!$res){
            $res = Db::table('amazon_fasin')->where('fasin',$fasin)->first();
            if($res){
                Redis::Hset('datacache:amazon_fasin',$fasin,json_encode($res));
                $res = json_decode(json_encode($res),true);
            }else{
                $res = false;
            }
        }else{
            $res = json_decode($res,true);
        }

        return $res;
    }

    /**
     * @Desc: 获取fasin绑定数据
     * @param $fasin
     * @param $shopId
     * @return false|mixed
     * @author: Liu Sinian
     * @Time: 2023/5/29 17:56
     */
    public function GetFasinCodeNew($fasin, $shopId = 0){
        if ($shopId){
            $res = Redis::Hget('datacache:amazon_fasin_bind',$fasin.'-'.$shopId);
            if(!$res){
                $res = Db::table('amazon_fasin_bind')->where('fasin',$fasin)->where('shop_id', $shopId)->select('fasin', 'shop_id', 'fasin_code')->first();
                if($res){
                    Redis::Hset('datacache:amazon_fasin_bind',$fasin.'-'.$shopId,json_encode($res));
                    $res = json_decode(json_encode($res),true);
                }else{
                    $res = false;
                }
            }else{
                $res = json_decode($res,true);
            }
        }else{
            $res = Redis::Hget('datacache:amazon_fasin_bind',$fasin);
            if(!$res){
                $res = Db::table('amazon_fasin_bind')->where('fasin',$fasin)->select('fasin', 'shop_id', 'fasin_code')->get();
                if($res){
                    Redis::Hset('datacache:amazon_fasin_bind',$fasin,json_encode($res));
                    $res = json_decode(json_encode($res),true);
                }else{
                    $res = false;
                }
            }else{
                $res = json_decode($res,true);
            }
        }


        return $res;
    }

    /**
     * @Desc: 库存变动日志
     * @param $locationId 库位id
     * @param $type 上下架类型 1上架 2下架
     * @param $num  库存变动数量
     * @param $customSkuId  库存skuid
     * @param $nowNum   库位当前剩余库存
     * @param $userId   操作人
     * @param $orderNo  清单号
     * @return mixed
     * @author: Liu Sinian
     * @Time: 2023/6/19 20:23
     */
    public function saveCloudhouseLocationLog($locationId, $type, $num, $customSkuId, $nowNum, $userId, $platformId, $orderNo = '', $target_location_id = 0, $remark = '')
    {
        $customSku = db::table('self_custom_sku')->where('id', $customSkuId)->first();
        $save = [
            'location_id' => $locationId,
            'type' => $type,
            'num' => $num,
            'custom_sku_id' => $customSkuId,
            'now_num' => $nowNum,
            'user_id' => $userId,
            'order_no' => $orderNo,
            'spu' => $customSku->spu ?? '',
            'spu_id' => $customSku->spu_id ?? 0,
            'custom_sku' => $customSku->custom_sku,
            'time' => date('Y-m-d H:i:s', microtime(true)),
            'target_location_id' => $target_location_id,
            'remark' => $remark
        ];

        $id = db::table('cloudhouse_location_log')->insertGetId($save);

        return $id;
    }

    /**
     * @Desc:链接代号获取合同下单数量
     * @param $fasinCode
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/6/27 14:44
     */
    public function getContractSkuList($fasinCode)
    {
        $list = db::table('cloudhouse_custom_sku as a')
            ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no')
            ->where('fasin_code', $fasinCode);
        $count = $list->count();
        $list = $list->get(['a.*']);
        $totalPrice = 0;
        foreach ($list as $item){
            $item->total_price = ceil($item->num * $item->price);
            $totalPrice += $item->total_price;
        }

        return ['count' => $count, 'list' => $list, 'total_price' => $totalPrice];
    }
    public function publicExport($params)
    {
        $func = new Datawhole();
        $result = $func->place_excel_expord($params);

        return $result;
    }

    //查询平台库存
    public function platformInventory($custom_sku_id,$warehouse_id,$platform){
        $location_data = DB::table('cloudhouse_location_num as a')->leftJoin('cloudhouse_warehouse_location as a','a.location_id','=','b.id');

        if(!$warehouse_id||$warehouse_id>2){
            $self_custom_data = DB::table('self_custom_sku');
        }


        if(is_array($custom_sku_id)){
            $location_data = $location_data->whereIn('a.custom_sku_id',$custom_sku_id);
            if(isset($self_custom_data)){
                $self_custom_data = $self_custom_data->whereIn('id',$custom_sku_id)->select('cloud_num','deposit_inventory')->get();
            }
        }else{
            $location_data = $location_data->where('a.custom_sku_id',$custom_sku_id);
            if(isset($self_custom_data)){
                $self_custom_data = $self_custom_data->where('id',$custom_sku_id)->select('cloud_num','deposit_inventory')->first();
            }
        }
        if($warehouse_id){
            $location_data = $location_data->where('a.warehouse_id',$warehouse_id);
            if(isset($self_custom_data)){

            }
        }
        if($platform){
            $location_data = $location_data->where('b.platform_ids','like','%'.$platform.'%');
        }

        $location_data = $location_data
            ->where('b.type',1)
            ->select('a.custom_sku_id','a.num','a.locaton_id','b.platform_ids')
            ->get();

        foreach ($location_data as $d){
            $locationId[] = $d->locaton_id;
        }
        array_unique($locationId);

        $lock_data = DB::table('goods_transfers_box_detail as a')
            ->leftJoin('goods_transfers_box as b','a.box_id','=','b.id')
            ->whereIn('b.box_code','like','box%')
            ->whereIn('a.location_ids',$locationId);
        if(is_array($custom_sku_id)){
            $lock_data = $lock_data->whereIn('a.custom_sku_id',$custom_sku_id);
        }else{
            $lock_data = $lock_data->where('a.custom_sku_id',$custom_sku_id);
        }
        $lock_data = $lock_data->select('box_num','shelf_num','custom_sku_id','location_ids','b.warehouse_id')->get();

        $lockArr = [];
        if(!$lock_data->isEmpty()){
            if($warehouse_id){
                foreach ($lock_data as $l){
                    if(isset($lockArr[$l->custom_sku_id])){
                        $lockArr[$l->custom_sku_id] += $l->box_num - $l->shelf_num;
                    }else{
                        $lockArr[$l->custom_sku_id] = $l->box_num - $l->shelf_num;
                    }

                }
            }else{
                foreach ($lock_data as $l){
                    if(isset($lockArr[$l->custom_sku_id])){
                        $lockArr[$l->custom_sku_id][$l->warehouse_id] += $l->box_num - $l->shelf_num;
                    }else{
                        $lockArr[$l->custom_sku_id][$l->warehouse_id] = $l->box_num - $l->shelf_num;
                    }

                }
            }
        }

        $customInventory = [];
        $locationInventory = [];
        if($warehouse_id){
            foreach ($location_data as $v){
                if(isset($customInventory[$v->custom_sku_id])){
                    $customInventory[$v->custom_sku_id] += $v->num;
//                    $locationInventory[$v->custom_sku_id][$v->location_id] += $v->num;
                }else{
                    $customInventory[$v->custom_sku_id] = $v->num;
//                    $locationInventory[$v->custom_sku_id][$v->location_id] = $v->num;
                }
            }

        }else{
            foreach ($location_data as $v){
                if(isset($customInventory[$v->custom_sku_id][$v->location_id])){
                    $customInventory[$v->custom_sku_id][$v->warehouse_id] += $v->num;
//                    $locationInventory[$v->custom_sku_id][$v->location_id] += $v->num;
                }else{
                    $customInventory[$v->custom_sku_id][$v->warehouse_id] = $v->num;
//                    $locationInventory[$v->custom_sku_id][$v->location_id] = $v->num;
                }
            }
        }

        return ['customInventory'=>$customInventory,'lockArr'=>$lockArr];

    }

    /**
     * @Desc:向下保留小数位  eg. 1.256 => 1.25; 1.999 => 1.99
     * @param $number
     * @param $decimal
     * @return string
     * @author: Liu Sinian
     * @Time: 2023/7/14 9:14
     */
    public function floorDecimal($number, $decimal = 2)
    {
        $res = sprintf("%01.".$decimal.'f', bcmul($number, 1, $decimal));
//        $res = bcmul($number, 1, $decimal);

        return $res;
    }

    /**
     * @Desc:获取fasin留言是否已回复
     * @param $fasin
     * @return int
     * @author: Liu Sinian
     * @Time: 2023/7/17 14:50
     */
    public function GetFasinMessageRead($fasin)
    {
        $res = Redis::Hget('datacache:fasin_message_read', $fasin);
        if (!$res) {
            $res = 0;
        }
        return $res;
    }

    /**
     * @Desc: 获取常量键值对列表
     * @param $array
     * @return array|mixed
     * @author: Liu Sinian
     * @Time: 2023/7/21 9:11
     */
    public function GetConstantList($array = [])
    {
        if (empty($array)){
            return array();
        }else{
            foreach ($array as $k => $v){
                $arr = [];
                foreach ($v as $_k => $_v){
                    $arr[] = [
                        'id' => $_k,
                        'name' => $_v
                    ];
                }
                $array[$k] = $arr;
            }
        }

        return $array;
    }


    //获取仓库信息
    public function GetWarehouse($warehouse_id){
        $res = Redis::Hget('datacache:warehouse', $warehouse_id);
        if (!$res) {
            $res = Db::table('cloudhouse_warehouse')->where('id', $warehouse_id)->first();
            if ($res) {
                Redis::Hset('datacache:warehouse', $warehouse_id, json_encode($res));

                $res = json_decode(json_encode($res), true);
            } else {
                $res = false;
            }
        } else {
            $res = json_decode($res, true);
        }

        return $res;
    }

    /**
     * @Desc: 获取工厂虚拟库存
     * @param  $array
     * @return array
     */

    public function GetFactoryNum($custom_sku_id){
        $in = DB::table('cloudhouse_custom_sku');
        $out = DB::table('goods_transfers as a')->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
            ->where('a.is_push','>',0)->where('a.out_house',4)->orWhere('in_house',4);
        if(isset($custom_sku_id)){
            $in = $in->whereIn('custom_sku_id',$custom_sku_id);
            $out = $out->whereIn('b.custom_sku_id',$custom_sku_id);
        }
        $in = $in->get()->toArray();
        $out = $out->select('a.out_house','a.in_house','b.transfers_num','b.receive_num','a.is_push','a.type_detail')->get()->toArray();
        $factory = array();
        foreach ($in as $v){
            if(isset($factory[$v->custom_sku_id])){
                $factory[$v->custom_sku_id] += $v->num;
            }else{
                $factory[$v->custom_sku_id] = $v->num;
            }
        }

        foreach ($out as $d){
            if($d->in_house==4&&$d->type_detail==9){
                if(isset($factory[$d->custom_sku_id])){
                    if($d->is_push!=3){
                        $factory[$v->custom_sku_id] -= $v->transfers_num;
                    }else{
                        $factory[$v->custom_sku_id] -= $v->receive_num;
                    }
                }else{
                    if($d->is_push!=3){
                        $factory[$v->custom_sku_id] = 0-$v->transfers_num;
                    }else{
                        $factory[$v->custom_sku_id] = 0-$v->receive_num;
                    }

                }
            }
            if($d->out_house==4&&$d->type_detaol==2){
                if(isset($factory[$d->custom_sku_id])){
                    if($d->is_push!=3){
                        $factory[$v->custom_sku_id] += $v->transfers_num;
                    }else{
                        $factory[$v->custom_sku_id] += $v->receive_num;
                    }
                }else{
                    if($d->is_push!=3){
                        $factory[$v->custom_sku_id] = $v->transfers_num;
                    }else{
                        $factory[$v->custom_sku_id] = $v->receive_num;
                    }
                }
            }
        }
    }

    //根据仓库和平台和sku获取库存数量
    public function GetInventoryByPlatformAndSku($warehouseId = 0, $customSkuId = 0, $platformId=0)
    {
        $res = DB::table('cloudhouse_location_num as a')
            ->leftJoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
            ->where('b.type',1)
            ->where(function ($query) use ($warehouseId) {
                if ($warehouseId) {
                    $query->where('b.warehouse_id', $warehouseId);
                }
            })
            ->where('a.custom_sku_id', $customSkuId)
            ->where('a.platform_id', $platformId)
            ->sum('a.num');
        if($res){
            return $res;
        }else{
            return 0;
        }
    }

    /**
     * @Desc:将数值金额转换为中文大写金额
     * @param $amount float 金额(支持到分)
     * @param $type   int   补整类型,0:到角补整;1:到元补整
     * @return mixed 中文大写金额
     * @author: Liu Sinian
     * @Time: 2023/8/13 21:03
     */
    public function convertAmountToCn($amount, $type = 0) {
        // 判断输出的金额是否为数字或数字字符串
        if(!is_numeric($amount)){
            return "要转换的金额只能为数字!";
        }

        // 金额为0,则直接输出"零元整"
        if($amount == 0) {
            return "零元整";
        }

        // 金额不能为负数
        if($amount < 0) {
            return "要转换的金额不能为负数!";
        }

        // 金额不能超过万亿,即12位
        if(strlen($amount) > 12) {
            return "要转换的金额不能为万亿及更高金额!";
        }

        // 预定义中文转换的数组
        $digital = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
        // 预定义单位转换的数组
        $position = array('仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '元');

        // 将金额的数值字符串拆分成数组
        $amountArr = explode('.', $amount);

        // 将整数位的数值字符串拆分成数组
        $integerArr = str_split($amountArr[0], 1);

        // 将整数部分替换成大写汉字
        $result = '';
        $integerArrLength = count($integerArr);     // 整数位数组的长度
        $positionLength = count($position);         // 单位数组的长度
        for($i = 0; $i < $integerArrLength; $i++) {
            // 如果数值不为0,则正常转换
            if($integerArr[$i] != 0){
                $result = $result . $digital[$integerArr[$i]] . $position[$positionLength - $integerArrLength + $i];
            }else{
                // 如果数值为0, 且单位是亿,万,元这三个的时候,则直接显示单位
                if(($positionLength - $integerArrLength + $i + 1)%4 == 0){
                    $result = $result . $position[$positionLength - $integerArrLength + $i];
                }
            }
        }

        // 如果小数位也要转换
        if($type == 0) {
            if (!isset($amountArr[1])){
                $result = $result . '整';
                return $result;
            }
            // 将小数位的数值字符串拆分成数组
            $decimalArr = str_split($amountArr[1], 1);
            // 将角替换成大写汉字. 如果为0,则不替换
            if($decimalArr[0] != 0){
                $result = $result . $digital[$decimalArr[0]] . '角';
            }
            // 将分替换成大写汉字. 如果为0,则不替换
            if($decimalArr[1] ?? 0 != 0){
                $result = $result . $digital[$decimalArr[1]] . '分';
            }
        }else{
            $result = $result . '整';
        }
        return $result;
    }


    /**
     * @Desc:将已有颜色组合为组合色
     * @param $spu_id  int 组合spuid
     * @param $color   array   颜色标识数组
     * @author: 严威
     * @Time: 2023/8/31 14:41
     */
    public function assemblyColor($color=array(),$spu_id){
        if(!empty($color)&&is_array($color)){
            $colorSon = implode(',',$color);
            $self_color_size = DB::table('self_color_size')->where('color_son',$colorSon)->select('id')->first();
            $base = DB::table('self_spu')->where('id',$spu_id)->select('base_spu_id','spu')->first();

            if($self_color_size){
                $spu_color = DB::table('self_spu_color')->where('base_spu_id',$base->base_spu_id)->where('spu',$base->spu)->where('color_id',
                    $self_color_size->id)->select('id')
                    ->first();
                if(empty($spu_color)){
                    $addColor = DB::table('self_spu_color')->insert(['base_spu_id'=>$base->base_spu_id,'spu'=>$base->spu,
                        'color_id'=>$self_color_size->id,'addtime'=>date('Y-m-d H:i:s'),'status'=>1]);
                    if($addColor){
                        return 1;
                    }else{
                        return 0;
                    }
                }else{
                    return 1;
                }
            }else{
                $max_color_size = DB::table('self_color_size')->where('color_class','=','Z')->orderBy('class_num','desc')->select('class_num')->first();
                if($max_color_size){
                    $insert['class_num'] = $max_color_size->class_num+1;
                }else{
                    $insert['class_num'] = 1;
                }
                $colorData = DB::table('self_color_size')->whereIn('identifying',$color)->select('name')->get();
                $colorName = [];
                foreach ($colorData as $c){
                    $colorName[] = $c->name;
                }
                $colorName = implode('+',$colorName);

                if($insert['class_num']<10){
                    $insert['identifying'] = 'Z0'.$insert['class_num'];
                    $insert['english_name'] = 'assembly0'.$insert['class_num'];
                }else{
                    $insert['identifying'] = 'Z'.$insert['class_num'];
                    $insert['english_name'] = 'assembly'.$insert['class_num'];
                }
                $insert['user_id'] = 1;
                $insert['color_class'] = 'Z';
                $insert['color_son'] = $colorSon;
                $insert['create_time'] = time();
                $insert['name'] = $colorName;
                $insert['type'] = 1;
                $insert['status'] = 1;
                $add = DB::table('self_color_size')->insertGetId($insert);
                if($add){
                    $spu_color = DB::table('self_spu_color')->where('base_spu_id',$base->base_spu_id)->where('spu',$base->spu)->where('color_id',$add)->select('id')
                        ->first();
                    if(empty($spu_color)){
                        $addColor = DB::table('self_spu_color')->insert(['base_spu_id'=>$base->base_spu_id,'spu'=>$base->spu,
                            'color_id'=>$add,'addtime'=>date('Y-m-d H:i:s'),'status'=>1]);
                        if($addColor){
                            return 1;
                        }else{
                            return 0;
                        }
                    }else{
                        return 1;
                    }
                }else{
                    return 0;
                }
            }
        }else{
            return 0;
        }
    }

    /**
     * @Desc:
     * @param $html 打印文本
     * @param $title 文件标题
     * @param $id 唯一标识
     * @return mixed
     * @throws \Exception
     * @author: Liu Sinian
     * @Time: 2023/9/4 14:22
     */
    public function publicSavePdf($html, $title, $id, $type, $userId)
    {
        if (empty($html)){
            throw new \Exception('打印页面数据不能为空！');
        }
        if (empty($title)){
            throw new \Exception('文件标题不能为空！');
        }
        if (empty($id)){
            throw new \Exception('唯一标识不可为空！');
        }
        if (empty($type)){
            throw new \Exception('任务类型不可为空！');
        }
        if (empty($userId)){
            throw new \Exception('操作人标识不可为空！');
        }
        $job = new PublicSavePdfController();
        try {
            $params = [
                'html' => $html,
                'title' => $title,
                'id' => $id,
                'type' => $type,
                'user_id' => $userId
            ];
            $job::runJob($params);

            return ['code' => 200, 'msg' => '加入队列成功!'];
        } catch(\Exception $e){
            return ['code' => 500, 'msg' => '加入队列失败!'.$e->getMessage()];
        }
    }

    public function getSavePdfPath($html, $title, $id)
    {
        require_once(app_path() . DIRECTORY_SEPARATOR . 'Libs' . DIRECTORY_SEPARATOR . 'tcpdf' . DIRECTORY_SEPARATOR . 'examples' . DIRECTORY_SEPARATOR . 'tcpdf_include.php');
        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        // 设置文档信息
        $pdf->SetCreator('L');
        $pdf->SetAuthor('L');
        $pdf->SetTitle($title);
        $pdf->SetSubject($title);
        $pdf->SetKeywords('TCPDF, PDF, PHP');

        // 设置页眉和页脚信息
        $pdf->SetHeaderData('', 0, '', '', [0, 0, 0], [255, 255, 255]);
        $pdf->setFooterData([0, 0, 0], [255, 255, 255]);

        // 设置页眉和页脚字体
        $pdf->setHeaderFont(['stsongstdlight', '', '10']);
        $pdf->setFooterFont(['stsongstdlight', '', '8']);

        //删除预定义的打印 页眉/页尾
//            $pdf->setPrintHeader($result['is_header'] ?? false);
//            $pdf->setPrintFooter($result['is_footer'] ?? false);

        // 设置默认等宽字体
        $pdf->SetDefaultMonospacedFont('courier');

        // 设置字体
//            $pdf->setFont('times');

        // 设置间距
        $pdf->SetMargins(10, 15, 15);//页面间隔
        $pdf->SetHeaderMargin(5);//页眉top间隔
        $pdf->SetFooterMargin(5);//页脚bottom间隔

        // 设置分页
        $pdf->SetAutoPageBreak(TRUE, 15);
        $pdf->setFontSubsetting(true);

        // set default font subsetting mode
        $pdf->setFontSubsetting(true);

        //设置字体 stsongstdlight支持中文
        $pdf->SetFont('stsongstdlight', '', 10);

        $pdf->Ln(5);

        // 设置密码
//            $pdf->SetProtection($permissions = array('print', 'modify', 'copy', 'annot-forms', 'fill-forms', 'extract', 'assemble', 'print-high'), $user_pass = '123456', $owner_pass = null, $mode = 0, $pubkeys = null );

        //第一页
        $pdf->AddPage();
        $pdf->writeHTML($html, true, false, true, true, 'center');

        //输出PDF
        $path = 'pdf' . DIRECTORY_SEPARATOR. time() .$title.$id.'.pdf';
        $pdf->Output(public_path().DIRECTORY_SEPARATOR.$path, 'F');//I输出、D下载

        return $path;
    }


    //根据spu获得最新合同价格
    public function GetSpuContractPrice($spu_id){
        $price = db::table('cloudhouse_contract')->where('spu_id',$spu_id)->orderby('create_time','desc')->first()->one_price??0;
        return  $price;
    }

    public function IdentifyingGetColorSize($identifying)
    {
        $color = Redis::Hget('datacache:identifying_get_color_size', $identifying);
        if (!$color){
            $res = db::table('self_color_size')
                ->where('identifying', $identifying)
                ->first();
            if (!empty($res)){
                $color = json_decode(json_encode($res), true);
                Redis::Hset('datacache:identifying_get_color_size', $identifying, json_encode($res));
            }else{
                $color = false;
            }
        }else{
            $color = json_decode($color, true);
        }

        return $color;
    }
    public function GetSpuColorImg($spu, $color_identifying)
    {
        $img = Redis::Hget('datacache:spu_color_imgs', $spu.'-'.$color_identifying);
        if (!$img) {
            $base_spu_id = $this->GetBaseSpuIdBySpu($spu);
            $color_id = $this->IdentifyingGetColorSize($color_identifying)['id'] ?? 0;
            $res = Db::table('self_spu_color')
                ->where('base_spu_id', $base_spu_id)
                ->where('img', '!=', '');
            if (!empty($color_id)){
                $res = $res->where('color_id', $color_id);
            }
            $res = $res->first();
            if (!empty($res->img)) {
                $img = $res->img;
                Redis::Hset('datacache:spu_color_imgs', $spu.'-'.$color_identifying, $img);
            } else {
                $img = '';
            }
        }
        return $img;
    }
}



